18_字符对象.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 字符型对应的js内部顶级对象 String
  11. var str = "hello";
  12. var str2 = "world";
  13. // 获取制定位置的字符 字符串起始位置是0
  14. console.log( str.charAt(0) );
  15. // 拼接字符串
  16. console.log(str.concat(str2));
  17. // 返回某个指定的字符串值在字符串中首次出现的位置。如果没有包含这个字符返回-1
  18. console.log(str.indexOf("w"));
  19. // 查找字符串中是否包含指定的子字符串。
  20. console.log(str.includes("hl"));
  21. // 提取字符串的片断,并在新的字符串中返回被提取的部分。
  22. // 第一个参数开始位置 第二参数结束位置(不包含结束位置)
  23. // 如果第二个参数不写截取到最后
  24. console.log(str.slice(1,4));
  25. // 从起始索引号提取字符串中指定数目的字符。
  26. // 第二个参数为截取个数
  27. console.log(str.substr(1,4))
  28. // trim 去除左右两边空格
  29. var str3 = " 你好 ";
  30. console.log(str3);
  31. console.log(str3.trim());
  32. // 把字符串分割为字符串数组。
  33. var str4 = "2026-1-9";
  34. console.log(str4.split("-"));
  35. var str5 = "abcdefg";
  36. console.log(str5.split(""));
  37. // 获取字符串长度
  38. console.log(str.length);
  39. </script>
  40. </body>
  41. </html>