在最新的 ECMAScript 2021 中,新增了 String.prototype.matchAll() 方法,它是基于正则表达式进行匹配字符串的方法,该方法返回一个迭代器(Iterator)对象,用于遍历所有匹配的结果。
语法
string.matchAll(regexp)
其中,regexp 表示正则表达式对象。
返回值
该方法返回一个迭代器(Iterator)对象,该对象包含所有匹配结果的详细信息。
实例代码
const str = '一个句子含有多个单词,其中一些词可能会被重复使用多次。'; const regExp = /\b\w+\b/g; const matchAllResult = str.matchAll(regExp); for (const match of matchAllResult) { console.log(match); }
上面的代码将输出以下结果:
-- -------------------- ---- ------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ -- ------ ------------------------------ ------- ---------- ------ ------ --- ------ ------------------------------ ------- ---------- ------- ------ --- ------ ------------------------------ ------- ---------- ------ ------ --- ------ ------------------------------ ------- ---------- ------ ------ --- ------ ------------------------------ ------- ---------- ------ ------ --- ------ ------------------------------ ------- ---------- ------ ------ --- ------ ------------------------------ ------- ----------展开代码
深入解析
- matchAllResult.next() 方法
String.prototype.matchAll() 方法所返回的迭代器(Iterator)对象具有 next() 方法,该方法可用于获取迭代器的下一个结果。
matchAllResult.next();
上面的代码将返回:
{value: ["一个", index: 0, input: "一个句子含有多个单词,其中一些词可能会被重复使用多次。", groups: undefined], done: false}
- 使用该方法的好处
我们可以在实际开发中使用该方法遍历文本(例如 HTML 或 Markdown),并从中提取所有链接、代码片段等等。
const str = '这是一个[链接](https://example.com)和一些内联`代码`示例。'; const regExp = /(?<=\[)([^\]]+)(?=\])|(?<=\()\S+(?=\))/g; const matchAllResult = str.matchAll(regExp); for (const match of matchAllResult) { console.log(match); }
上面的代码将输出以下结果:
["链接", index: 6, input: "这是一个[链接](https://example.com)和一些内联`代码`示例。", groups: undefined] ["https://example.com", index: 8, input: "这是一个[链接](https://example.com)和一些内联`代码`示例。", groups: undefined] ["代码", index: 20, input: "这是一个[链接](https://example.com)和一些内联`代码`示例。", groups: undefined]
注意事项
- 该方法只能在支持 ES2021 的环境下使用。
- 该方法返回的迭代器一旦访问完所有结果,就不能重置并重新使用,如果需要多次使用,需要重新调用
string.matchAll(regexp)
方法,获取一个新的迭代器。 - 在正则表达式中使用捕获组(Capture Group)时,matchAllResult 中的结果将包含 groups 属性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67b6cb0d306f20b3a6310f3a