ES9(ECMAScript 2018)为我们带来了许多新的语言特性和 API,其中一项值得关注的更新就是正则表达式方法的新功能 - matchAll。虽然 match( ) 方法已经足够强大,但是 matchAll( ) 的出现让我们可以更加高效、准确的匹配字符串。
什么是 matchAll?
matchAll( ) 方法返回一个正则表达式的匹配结果,这个结果是一个迭代器(iterator),包含了所有匹配的结果。之前 match( ) 方法只会返回第一个匹配结果,而 matchAll( ) 方法可以获取到字符串中的所有匹配结果。
matchAll( ) 方法的语法如下:
str.matchAll(regexp)
其中str表示要执行匹配的字符串,regexp为正则表达式对象。
如何使用 matchAll?
使用 matchAll( ) 方法的步骤如下:
- 创建正则表达式对象
- 使用matchAll( ) 方法对字符串进行匹配
- 使用for...of循环遍历匹配结果
下面是一个例子,演示如何使用 matchAll( ) 方法:
const str = 'hello world hello mars'; const re = /hello\s(\w+)/g; const matches = str.matchAll(re); for (const match of matches) { console.log(match[1]); }
输出结果是:
world
mars
在这个例子中,正则表达式 /hello\s(\w+)/g 会匹配所有以 "hello "开头且其后跟着一个单词的字符串。 随后,使用matchAll( ) 方法和for...of循环遍历匹配结果,将每一个匹配的单词进行了打印输出。
我们可以看到,matchAll( ) 方法返回的是一个迭代器。具体来说,对于每一次匹配,它返回一个数组,其中的第一个元素是匹配的全部结果,剩下的则是附加的捕获结果。在这个例子中,我们使用了 \w+ 来捕获了每一个匹配单词的值。由于我们只关心第二个捕获结果,因此我们只打印了匹配结果的第二个元素(因为数组索引是从0开始计数的)。
matchAll 与 match 的区别
前面已经提到,matchAll( ) 方法与之前的 match( ) 方法有区别。具体来说,match( ) 方法只会返回第一个匹配的结果,而 matchAll( ) 则能返回字符串中所有的匹配结果。
下面是一个例子,展示了 match( ) 方法和 matchAll( ) 方法的区别:
const str = 'hello world hello mars'; const re = /hello\s(\w+)/g; console.log(str.match(re)); console.log([...str.matchAll(re)]);
输出结果是:
[ 'hello world', 'hello mars' ] [ [ 'hello world', 'world', index: 0, input: 'hello world hello mars', groups: undefined ], [ 'hello mars', 'mars', index: 12, input: 'hello world hello mars', groups: undefined ] ]
对于第一个日志,我们使用了 match( ) 方法获取字符串中指定正则表达式的第一个匹配结果。对于第二个日志,我们使用了 matchAll( ) 方法将字符串中所有指定的匹配结果都提取了出来。
兼容性
matchAll( ) 方法在ES9 (ECMAScript 2018)中被引入,因此在旧版本的浏览器中可能不被支持。 但是,您可以使用以下代码来进行检查:
if (!String.prototype.matchAll) { console.log('polyfilling matchAll'); String.prototype.matchAll = polyfill; }
总结
ES9 带来了 matchAll( ) 方法的更新,它可以让你更方便地匹配字符串,而不用担心漏掉其中的匹配结果。使用 matchAll( ) 方法可以取代 match( ) 方法,更容易实现更有用的正则表达式匹配操作。
最后预祝您在前端开发的道路上越走越远!
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6501c42195b1f8cacdf668a4