matchAll()
方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。
{{EmbedInteractiveExample("pages/js/string-matchall.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
str.matchAll(regexp)
regexp
正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj)
将其转换为一个 RegExp
。
一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。
在 matchAll
出现之前,通过在循环中调用regexp.exec来获取所有匹配项信息(regexp需使用/g标志:
const regexp = RegExp('foo*','g');
const str = 'table football, foosball';
while ((matches = regexp.exec(str)) !== null) {
console.log(`Found ${matches[0]}. Next starts at ${regexp.lastIndex}.`);
// expected output: "Found foo. Next starts at 9."
// expected output: "Found foo. Next starts at 19."
}
如果使用matchAll
,就可以不必使用while循环加exec方式(且正则表达式需使用/g标志)。使用matchAll
会得到一个迭代器的返回值,配合 for...of
, array spread, or Array.from()
可以更方便实现功能:
const regexp = RegExp('foo*','g');
const str = 'table football, foosball';
let matches = str.matchAll(regexp);
for (const match of matches) {
console.log(match);
}
// Array [ "foo" ]
// Array [ "foo" ]
// matches iterator is exhausted after the for..of iteration
// Call matchAll again to create a new iterator
matches = str.matchAll(regexp);
Array.from(matches, m => m[0]);
// Array [ "foo", "foo" ]
matchAll
的另外一个亮点是更好地获取分组捕获。因为当使用match()
和/g标志方式获取匹配信息时,分组捕获会被忽略:
var regexp = /t(e)(st(\d?))/g;
var str = 'test1test2';
str.match(regexp);
// Array ['test1', 'test2']
使用 matchAll
可以通过如下方式获取分组捕获:
let array = [...str.matchAll(regexp)];
array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]
Specification | Status |
---|---|
String.prototype.matchAll | Stage 3 |
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
matchAll | Chrome Full support 73 | Edge No support No | Firefox Full support 67 | IE No support No | Opera Full support 60 | Safari No support No | WebView Android Full support 73 | Chrome Android Full support 73 | Edge Mobile No support No | Firefox Android Full support 67 | Opera Android Full support Yes | Safari iOS No support No | Samsung Internet Android Full support Yes | nodejs No support No |