29.字符串常用方法及字符串模板

  • 在js中字符串可以看做一个特殊的数组,所以大部分数组的属性/方法字符串都可以使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1.获取字符串长度  .length
let str = "abcd";
console.log(str.length);

2.获取某个字符 [索引] / charAt
let str = "abcd";
let ch = str[1];
let ch = str.charAt(1);
console.log(ch);

3.字符串查找 indexOf / lastIndexOf / includes
let str = "vavcd";
let index = str.indexOf("v");
let index = str.lastIndexOf("v");
console.log(index);
let result = str.includes("p");//false
console.log(result);

4.拼接字符串 concat / +
let str1 = "www";
let str2 = "it666";
let str = str1 + str2; // 推荐
let str = str1.concat(str2);
console.log(str);

5.截取子串 slice / substring / substr
let str = "abcdef";
// let subStr = str.slice(1, 3);
// let subStr = str.substring(1, 3);
let subStr = str.substr(1, 3);
console.log(subStr);
  • stringObject.substr(start,length),length从start的index开始截取几个元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
1.字符串切割
let arr = [1, 3, 5];
let str = arr.join("-");//数组转为字符串,1-3-5
console.log(str);
let str = "1-3-5";
let arr = str.split("-");//[ '1', '3', '5' ]
console.log(arr);

2.判断是否以指定字符串开头 ES6
let str = "http://www.it666.com";
let result = str.startsWith("www");
console.log(result);


3.判断是否以指定字符串结尾 ES6
let str = "lnj.jpg";
let result = str.endsWith("png");
console.log(result);


4.字符串模板 ES6
let str = "";
let str = '';
let str = `www.it666.com`;
console.log(str);
console.log(typeof str);

let str = "<ul>\n" +
" <li>我是第1个li</li>\n" +
" <li>我是第2个li</li>\n" +
" <li>我是第3个li</li>\n" +
"</ul>";

let str = `<ul>
<li>我是第1个li</li>
<li>我是第2个li</li>
<li>我是第3个li</li>
</ul>`;

let name = "lnj";
let age = 34;
// let str = "我的名字是" + name + ",我的年龄是" + age;
let str = `我的名字是${name},我的年龄是${age}`;
console.log(str);