前言:
ES6为我们提供了更多方便的字符串操作,这里只写了常用的,详情请参考官网。
新增的实例方法:
(实例方法 都需要先声明实例才能使用)
方法 | 描述 |
---|---|
includes(string, position) | 判断字符串中是否包含指定字符串,返回值是布尔值 |
startsWith(string, position) | 判断字符串的开头是否包含指定字符串,返回值是布尔值 |
endsWith(string, position) | 判断字符串的尾部是否包含指定字符串,返回值是布尔值 |
repeat(n) | repeat() 方法返回一个新字符串,表示将原字符串重复n 次。 |
字符串补全 | 第一个参数是补全后的字符串长度,第二个参数是用于补全的字符串 |
padStart(length, str) | 用于头部补全 |
padEnd(length, str) | 用于尾部补全 |
去除空格 | |
trimStart() | 消除字符串头部的空格 |
trimEnd() | 消除尾部的空格 |
正则匹配 | |
matchAll() | 方法返回一个正则表达式在当前字符串的所有匹配 |
1.includes( ), startsWith( ), endsWith( ) 实例方法
(1)当只有一个参数时:
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
(2)这三个方法都支持第二个参数,表示开始搜索的位置:
let s = 'Hello world!';
s.startsWith('world', 6) // true,从第六个位置开始找,找到结尾
s.endsWith('Hello', 5) // true,从第六个位置开始,向着开头找
s.includes('Hello', 6) // false, 从第六个位置开始找,找到结尾
2.repeat()实例方法
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana" ,小数会被向下取整
// 负数,和Infinity,会报错
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
'na'.repeat(NaN) // "" ,NaN 等于0
3.padStart(),padEnd()实例方法
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
// 如果省略第二个参数,默认使用空格补全长度。
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
4.trimStart(),trimEnd()实例方法
注意:它们返回的都是新字符串,不会修改原始字符串。
const s = ' abc ';
s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"
6.matchAll( ) 实例方法
const string = 'test1test2test3';
// g 修饰符加不加都可以
const regex = /t(e)(st(\d?))/g;
for (const match of string.matchAll(regex)) {
console.log(match);
}
// ["test1", "e", "st1", "1", index: 0, input: "test1test2test3"]
// ["test2", "e", "st2", "2", index: 5, input: "test1test2test3"]
// ["test3", "e", "st3", "3", index: 10, input: "test1test2test3"]
不使用matchAll:
var regex = /t(e)(st(\d?))/g;
var string = 'test1test2test3';
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match);
}
console.log(matches);
// [
// ["test1", "e", "st1", "1", index: 0, input: "test1test2test3"],
// ["test2", "e", "st2", "2", index: 5, input: "test1test2test3"],
// ["test3", "e", "st3", "3", index: 10, input: "test1test2test3"]
// ]