ECMAScript 2021 引入了一些新的字符串函数,使得字符串的处理更加高效和方便。本文将对其中五个重要的函数进行介绍,并附上相关的示例代码。
1. String.prototype.replaceAll()
replaceAll() 函数可以在一个字符串中查找并替换所有的匹配项。它接受两个参数:第一个参数是要替换的字符串或正则表达式,第二个参数是替换后的字符串或处理函数。如果第一个参数是字符串,则只会替换第一个匹配项;如果第一个参数是正则表达式,则会替换所有匹配项。
const str = 'hello world!';
const newStr = str.replaceAll('l', 'x');
console.log(newStr); // 'hexxo worxd!'
const str2 = 'hello world!';
const newStr2 = str2.replaceAll(/l/g, 'x');
console.log(newStr2); // 'hexxo worxd!'2. String.prototype.trimStart() 和 String.prototype.trimEnd()
trimStart() 和 trimEnd() 函数可以分别去除一个字符串的开头和结尾的空格符或其他指定字符。它们不接受任何参数,且都返回新的字符串。
const str = ' hello world! ';
const newStr = str.trimStart().trimEnd();
console.log(newStr); // 'hello world!'
const str2 = 'helloooo world!';
const newStr2 = str2.trimEnd('o');
console.log(newStr2); // 'helloooo world'3. String.prototype.matchAll()
matchAll() 函数可以在一个字符串中查找所有的匹配项,并返回一个迭代器。它接受一个正则表达式作为参数,可以遍历所有的匹配项,每个匹配项包含匹配的内容和组信息。
const str = 'hello world, hi there';
const reg = /\b\w{5}\b/g;
const matches = str.matchAll(reg);
for (const match of matches) {
console.log(match[0]);
}
// 'hello'
// 'there'4. String.prototype.startsWith() 和 String.prototype.endsWith()
startsWith() 和 endsWith() 函数可以分别判断一个字符串是否以指定的字符串或正则表达式开头或结尾。它们接受一个参数,可以是一个字符串或正则表达式。如果参数是字符串,则仅对首尾进行匹配;如果参数是正则表达式,则对整个字符串进行匹配。
const str = 'hello world!';
console.log(str.startsWith('hello')); // true
console.log(str.endsWith('world!')); // true
const str2 = 'hello, world!';
console.log(str2.startsWith(/\w+/)); // true
console.log(str2.endsWith(/world\S/)); // true5. String.prototype.replaceAllNamed()
replaceAllNamed() 函数是一个实验性 API,推荐在生产环境中谨慎使用。它可以在一个字符串中查找并替换所有的命名组匹配项。它接受两个参数:第一个参数是字符串模板,第二个参数是替换后的字符串或处理函数。
const str = '2022-02-14';
const newStr = str.replaceAllNamed(
'{year}-{month}-{day}',
({ year, month, day }) => `${day}.${month}.${year}`
);
console.log(newStr); // '14.02.2022'以上是 ECMAScript 2021 中五个重要的字符串函数的介绍和示例代码。它们的引入使得字符串处理更加高效和方便,我们应该善加利用。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d64157a941bf7134bf344a