2.字符串的遍历器接口
ES6为字符串添加了遍历器接口,使得字符串也可以使用for…of循环遍历
for (let codePoint of 'foo') {
console.log(codePoint); //output: f o o
}
3.直接输入U+2028和U+2029
JavaScript 规定有5个字符,不能在字符串里面直接使用,只能使用转义形式。
- U+005C:反斜杠(reverse solidus)
- U+000D:回车(carriage return)
- U+2028:行分隔符(line separator)
- U+2029:段分隔符(paragraph separator)
- U+000A:换行符(line feed) ES2019允许 JavaScript 字符串直接输入 U+2028(行分隔符)和 U+2029(段分隔符)。
4.JSON.stringify()改造
5.模版字符串
模版字符串使用反引号标识,可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
//普通变量
`In js '\n' is a line-feed`
//多行字符串
`In js this is
not legal`
console.log(`string text line 1
string text line 2`);
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
在模版字符串中想要使用反引号,需要在前面加反斜杠转义
let greeting = `\`You\` World!`;
如果在模版字符串中便是多行字符串,所有的空格和缩进会被保留在输出之中。
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`);
如果想要删除,可以使用trim方法
$('#list').html(`
<ul>
<li> first </li>
<li> second </li>
</ul>
`.trim());
模版字符串中嵌入变量,需要将变量名写在${}之中。模版字符串中也可以调用函数
function authorize(user, acton) {
if (!user.hasPrivilege(action) {
throw new Error(`User ${user.name} is not authorized to do ${action}`)
}
}
`foo ${authorize()} `
字符串的新增方法
5.实例方法includes,startsWith,endsWith
includes()返回布尔值,表示是否找到了参数字符串
startsWith()返回布尔值,表示参数字符串是否在原字符串的头部
endsWith()返回布尔值,表示参数字符串是否在原字符串尾部
let s = 'Hello World!';
s.startsWith('Hello'); //output: true
s.endsWith('!'); //output: true
s.includes('o'); //output: truea
这三个方法都支持第二个参数,表示开始搜索的位置。
let s = 'Hello world';
s.startsWith('world', 6);
s.endsWith('Hello', 5);
s.includes('Hello', 6);
6.实例方法:repeat()
repeat方法返回一个新字符串,表示将字符串重复n次
'x'.repeat(3); //output: xxx
'hello'.repeat(2); //output: hellohello
如果参数是小数,会取整
'na'.repeat(2.9) // "nana"
如果参数是负数或者Infinity,会报错
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
7.实例方法:padStart(), padEnd()
如果某个字符串不够指定长度,会在头部或者尾部补全,padStart()用于头部补全,padEnd()用于尾部补全
'x'.padStart(5, 'abc'); //output: abcax
'x'.padStart(4, 'x'); //output: xxxx
'x'.padEnd(5, 'ab'); //output: xabab
'x'.padEnd(2, 'ab'); //output: xa
上面两个方法一共接受两个参数,第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串。
如果原字符串长度等于或大于最大长度,则字符串补全不生效并返回原字符串。如果省略第二个参数,则默认使用空格补全长度。
8.实例方法:trimStart(), trimEnd()
trimStart方法消除字符串头部的空格,trimEnd方法消除字符串尾部的空格,他们返回的都是新字符串,不会修改原始字符串
const s = ' abc ';
s.trim();
s.trimStart();
s.trimEnd();
9.实例方法:matchAll
返回一个正则表达式在当前字符串的所有匹配。
10.实例方法:replaceAll
replace方法是替换第一个匹配。例如:
'aaabbbccc'.replace('b', '_'); //output: 'aaa_bbccc'
如果要替换所有的匹配,那么就必须使用正则表达式的g修饰符(全局)
'aaabbbccc'.replaceAll(/b/g, '_'); //output: 'aaa___ccc'
而replaceAll方法也可以一次性替换所有匹配
'aabbcc'.replaceAll('b', '_') //output:'aa__cc'
11.实例方法:at
at方法接受一个整数作为参数,返回参数指定位置的字符。