concat

  1. <script>
  2. var str = "hello";
  3. var s = "world";
  4. console.log(str.concat(" ").concat(s));//hello world
  5. </script>

字符串模板

作用:可以在字符串中使用变量

  1. <script>
  2. var str = 10;
  3. var b = "hello";
  4. console.log(str+b);
  5. var sum = `${str}hello`;
  6. console.log(sum)
  7. </script>

slice(startIndex,endIndex)

  1. <script>
  2. var str ="hello";
  3. console.log(str[0]);//h
  4. console.log(str.slice(0,3))//hel
  5. </script>

substr(index,length) \substring(startIndex,endIndex)

  1. <script>
  2. var str = "hello";
  3. console.log(str.substr(2,3));//llo
  4. console.log(str.substring(0,2))//he
  5. </script>

length 字符串的长度

  1. <script>
  2. var str = "hello";
  3. console.log(str.length)//5
  4. var s = "故事的结尾,心上人";
  5. console.log(handleStr(s))//故事的结尾...
  6. function handleStr(value) {
  7. if (value.length > 5) {
  8. return value.slice(0, 5) + "..."
  9. }
  10. return value;
  11. }
  12. </script>

charAt

输出某一位下标值的字符

  1. <script>
  2. var str = "hello";
  3. console.log(str.charAt(1))//e
  4. </script>

indexof

输出某一字符的下标值

  1. <script>
  2. var str ="hello";
  3. console.log(str.indexOf("h"))//0
  4. console.log(str.indexOf("h"))//-1
  5. </script>

search

  1. <script>
  2. /* search 返回值的下标,没有返回-1,和indexOf类似 */
  3. var str = "你是谁";
  4. var index = str.search("你");
  5. console.log(index)
  6. console.log(str.indexOf("他"))
  7. </script>

match

  1. <script>
  2. /* match返回匹配的字符,返回一个数组 */
  3. var str = "helllllo";
  4. var arr = str.match("l");
  5. var arr1 = str.match("a");
  6. console.log(arr[0]);//l
  7. console.log(arr1);//null
  8. </script>

includes

字符串是否包含某位(多位)字符

  1. <script>
  2. var str ="hello";
  3. console.log(str.includes("he"))//true
  4. </script>

replace

  1. <script>
  2. /* replace可以替换字符 */
  3. var str = "hello";
  4. console.log(str.replace("l","*"))
  5. </script>

split

  1. <script>
  2. /* split(seprate) */
  3. var str ="hello";
  4. var arr = str.split("");
  5. console.log(str.split())//["hello"]
  6. console.log(arr);//["h", "e", "l", "l", "o"]
  7. console.log(str.split("e"))//["h", "llo"]
  8. </script>

例子(将hello反转为olleh)

  1. <script>
  2. var str = "hello"
  3. var arr = str.split("");
  4. arr.reverse();
  5. var s = arr.join("")
  6. console.log(s);
  7. </script>

trim

  1. <script>
  2. httpList()
  3. var a = " hello world "
  4. var b = a.trim()
  5. console.log(a.length)// hello world /
  6. console.log(b.length)//hello world
  7. console.log(a.length)//16
  8. console.log(b.length)//11
  9. </script>

字符串转成正则表达式

  1. var str = "/\\" + left[i] + "/";
  2. var reg = eval(str)