本篇衔接”详解JavaScript的String “这篇文章

一、字符串检测

1、indexOf()

方法从字符串开头开始查找子字符串,如果包含则返回下标,反之则返回 -1

1
2
3
let string = "hello world";
console.log(string.indexOf("o")); // 4
console.log(string.indexOf("B")); // -1

2、lastIndexOf()

方法从字符串末尾开始查找子字符串,如果包含则返回下标,反之则返回 -1

1
2
3
let string = "hello world";
console.log(string.lastIndexOf("o")); // 4
console.log(string.lastIndexOf("B")); // -1

二、字符串包含

1、includes()

ES6新增,用于检测字符串、数组等中是否包含该值,以布尔值的形式返回

1
2
3
let string = "hello world";
console.log(string.includes("o")); // true
console.log(string.includes("B")); // false

2、startsWith()

ES6新增,用于检测字符串、数组等中是否以某个字符串开头,以布尔值的形式返回

1
2
3
let string = "hello world";
console.log(string.startsWith("h")); // true
console.log(string.startsWith("B")); // false

3、endsWith()

ES6新增,用于检测字符串、数组等中是否以某个字符串结尾,以布尔值的形式返回

1
2
3
let string = "hello world";
console.log(string.endsWith("d")); // true
console.log(string.endsWith("B")); // false

上面的includes()startsWith() 方法只接受两个参数(可选)。第一个参数,表示开始搜索的位置。如果传入第二个参数,则意味着这两个方法会从指定位置向着字符串末尾搜索,忽略该位置之前的所有字符。
endsWith() 也只接受两个参数。第一个参数,表示应该当作字符串末尾的位置。如果不提供这个参数,那么默认就是字符串长度。如果提供这个参数,那么就好像字符串只有那么多字符一样。

1
2
3
4
5
6
7
8
let message = "foobarbaz";
console.log(message.startsWith("foo")); // true
console.log(message.startsWith("foo", 1)); // false
console.log(message.includes("bar")); // true
console.log(message.includes("bar", 4)); // false
let message = "foobarbaz";
console.log(message.endsWith("bar")); // false
console.log(message.endsWith("bar", 6)); // true

三、字符串空格

1、trim()

清除所有空格

1
2
let string = "hello world";
console.log(string.trim()); // helloworld

2、trimLeft()

清除左侧空格

1
2
let string = " hello world";
console.log(string.trimLeft()); // hello world

3、trimRight()

清除右侧空格

1
2
let string = "hello world ";
console.log(string.trimRight()); // hello world

四、repeat()

表示要将字符串复制多少次,然后返回拼接所有副本后的结果。

1
2
3
let string = "na ";
console.log(string.repeat(16)+ "batman");
// na na na na na na na na na na na na na na na na batman

五、填充字符串

1、padStart()

如果小于指定长度,则在开始处填充字符,直至满足长度条件。第一个参数是长度,第二个参数是填充字符串(可选),默认为空格。

2、padEnd()

如果小于指定长度,则在结尾处填充字符,直至满足长度条件。第一个参数是长度,第二个参数是填充字符串(可选),默认为空格。

1
2
3
4
5
let string = "foo";
console.log(string.padStart(6)); // " foo"
console.log(string.padStart(9, ".")); // "......foo"
console.log(string.padEnd(6)); // "foo "
console.log(string.padEnd(9, ".")); // "foo......"

六、字符串大小写转换

1、toLowerCase() 、toLocaleLowerCase()

将大写转为小写

1
2
3
let string = "HELLO"
console.log(string.toLowerCase())//hello
console.log(string.toLocaleLowerCase())//hello

2、toUpperCase()、toLocaleUpperCase()

将小写转为大写

1
2
3
let string = "hello"
console.log(string.toUpperCase())//HELLO
console.log(string.toLocaleUpperCase())//HELLO