ES2020 中的字符串改进和正则表达式
在 ES2020 中,JavaScript 的字符串和正则表达式得到了一些改进。本文将介绍这些改进,并提供一些示例代码和实际应用场景。
一、字符串改进
ES2020 中,字符串新增了三个实例方法和一项新功能:
String.prototype.matchAll()方法
该方法用于在字符串中查找所有匹配正则表达式的子串,并将它们作为迭代器返回。这个方法返回的迭代器可以被迭代,每次迭代返回一个数组,数组中包含当前匹配的字符串和匹配的子串(如果正则表达式定义了捕获组,则还会包含捕获组的值)。
示例代码:
// www.javascriptcn.com code example
const str = 'hello, world!';
const regex = /\b\w+\b/g;
for (const match of str.matchAll(regex)) {
console.log(match);
}
// 输出:
// ["hello", index: 0, input: "hello, world!", groups: undefined]
// ["world", index: 7, input: "hello, world!", groups: undefined]String.prototype.trimStart()和String.prototype.trimEnd()方法
这两个方法分别用于去除字符串开头和结尾的空格和空白字符。
示例代码:
const str = ' hello, world! '; console.log(str.trimStart()); // "hello, world! " console.log(str.trimEnd()); // " hello, world!"
- 新增的
\p{…}类别
该类别可以用于匹配任何 Unicode 字符属性。例如,\p{Letter} 匹配所有 Unicode 字母字符;\p{Number} 匹配所有数字字符;\p{Emoji} 匹配所有 Emoji 字符。
示例代码:
const regex = /\p{Emoji}/gu;
console.log(regex.test('💩')); // true
console.log(regex.test('hello')); // false- 全局可选的
s标志
这个标志用于匹配任何字符(包括换行符)。
示例代码:
const regex = /hello.world/s;
console.log(regex.test('hello\nworld')); // true二、正则表达式改进
ES2020 的正则表达式也新增了一些功能:
- 可选捕获组
在 ES2020 中,捕获组可以被标记为可选的。这样,如果正则表达式匹配时,可选捕获组没有匹配到任何内容,那么捕获组的值将会是 undefined。
示例代码:
const regex = /^(\d{4})?-?(\d{4})$/;
console.log('1234-5678'.match(regex)); // ["1234-5678", "1234", "5678"]
console.log('12345678'.match(regex)); // ["12345678", undefined, "1234"]Promise.allSettled()方法
这个方法用于并发运行多个异步任务,并等待它们全部结束。与 Promise.all() 不同的是,Promise.allSettled() 不会在任何一个任务出现错误时停止运行,而是等待全部任务都结束后返回一个数组,数组中包含每个任务的结果(包括成功和失败)。
示例代码:
// www.javascriptcn.com code example
async function fetchUrl(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
Promise.allSettled([
fetchUrl('/api/user/1'),
fetchUrl('/api/user/2'),
fetchUrl('/api/user/3')
]).then((results) => {
results.forEach(({ status, value, reason }) => {
if (status === 'fulfilled') {
console.log(value);
} else {
console.error(reason);
}
});
});综上所述,ES2020 中的字符串改进和正则表达式为我们提供了更好的字符串操作和更强大的正则表达式功能,这些改进在实际开发中会有很大的应用场景。切记,在使用这些功能时,要时刻注意性能和兼容性问题。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d8043aa941bf7134e4c6dd