在 ES11 中,新增了 String.prototype.matchAll() 方法,它可以更方便地匹配字符串中的所有符合条件的子串。与之前的 String.prototype.match() 方法相比,它可以返回一个迭代器,方便我们遍历所有匹配的结果。本文将详细介绍这两个方法的使用,以及它们的区别和优缺点。
String.prototype.match() 方法
String.prototype.match() 方法可以用正则表达式匹配字符串中的子串,返回一个数组。例如:
const str = 'hello world'; const matches = str.match(/o/g); console.log(matches); // ['o', 'o']
这里的正则表达式 /o/g 表示全局匹配所有的字符 o。match() 方法返回的是一个数组,其中包含了所有匹配的结果。
但是,match() 方法存在一些问题。例如,如果我们想匹配一个字符串中所有符合条件的子串,但是正则表达式中没有使用全局标志 g,那么它只会返回第一个匹配的结果。
const str = 'hello world'; const matches = str.match(/o/); console.log(matches); // ['o']
这时,我们可以使用 String.prototype.matchAll() 方法来解决这个问题。
String.prototype.matchAll() 方法
String.prototype.matchAll() 方法可以用于匹配字符串中所有符合条件的子串,返回一个迭代器,可以用 for...of 循环遍历所有匹配结果。例如:
const str = 'hello world';
const matches = str.matchAll(/o/g);
for (const match of matches) {
console.log(match);
}这里的正则表达式 /o/g 表示全局匹配所有的字符 o。matchAll() 方法返回的是一个迭代器,可以用 for...of 循环遍历所有匹配的结果。
需要注意的是,matchAll() 方法返回的迭代器并不是一个数组,而是一个可迭代对象。如果我们需要将其转换为数组,可以使用 Array.from() 方法。
const str = 'hello world'; const matches = Array.from(str.matchAll(/o/g)); console.log(matches); // [['o', index: 4, input: 'hello world'], ['o', index: 7, input: 'hello world']]
这里使用了 Array.from() 方法将迭代器转换为了数组。其中,每个数组元素都是一个匹配结果,包含了匹配的字符串、匹配位置和原始字符串。
区别与优缺点
String.prototype.matchAll() 方法与 String.prototype.match() 方法的最大区别在于,前者返回的是一个迭代器,可以遍历所有匹配的结果,而后者只返回第一个匹配的结果。这使得 matchAll() 方法更加灵活,可以用于匹配任意数量的子串。
但是,matchAll() 方法也存在一些缺点。由于它返回的是一个迭代器,因此无法直接使用数组的一些方法,例如 map()、filter() 和 reduce()。如果需要使用这些方法,需要先将迭代器转换为数组。
此外,matchAll() 方法也不支持 IE 浏览器,因此在编写兼容性较高的代码时需要注意。
示例代码
下面是一个使用 String.prototype.matchAll() 方法的示例代码。它可以匹配一段文本中所有包含关键词的句子,并将其加粗显示。
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ES11 中 String.prototype.matchAll() 与 String.prototype.match() 方法演示</title>
</head>
<body>
<div id="content">
<p>JavaScript is a programming language that is widely used in web development. It is a high-level language that is easy to learn and use. JavaScript is used to create dynamic and interactive web pages.</p>
<p>There are many JavaScript frameworks and libraries that make it easier to develop web applications, such as React, Angular and Vue. These frameworks provide a lot of useful features and tools, and can help developers to create complex web applications more efficiently.</p>
</div>
<script>
const content = document.getElementById('content').innerHTML;
const keywords = ['JavaScript', 'web development', 'React', 'Angular', 'Vue'];
const regex = new RegExp(`(${keywords.join('|')})`, 'gi');
const matches = Array.from(content.matchAll(regex));
for (const match of matches) {
const sentence = match.input.substring(0, match.index).split('.').pop() + match[0] + match.input.substring(match.index + match[0].length).split('.')[0];
const highlighted = `<b>${match[0]}</b>`;
const newSentence = sentence.replace(match[0], highlighted);
const newContent = match.input.replace(sentence, newSentence);
document.getElementById('content').innerHTML = newContent;
}
</script>
</body>
</html>在这个示例代码中,我们首先获取了一个包含文本的 div 元素。然后,定义了一个包含关键词的数组和一个正则表达式,用于匹配文本中所有包含关键词的句子。接着,使用 matchAll() 方法获取了所有匹配的结果,并使用 for...of 循环遍历每个匹配结果。在循环中,首先获取了匹配结果所在的句子,然后将关键词加粗显示,并将新的句子替换原来的句子。最后,将新的文本显示在了 div 元素中。
通过这个示例代码,我们可以更加深入地了解 String.prototype.matchAll() 方法的使用。它可以帮助我们更加方便地匹配字符串中的子串,提高代码的效率和可读性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d42af0a941bf71347db846