matchAll() 方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。

{{EmbedInteractiveExample("pages/js/string-matchall.html")}}

语法

str.matchAll(regexp)

参数

regexp

    正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。

返回值

一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。

例子

Regexp.exec() 和 matchAll()

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

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
matchAllChrome Full support 73Edge No support NoFirefox Full support 67IE No support NoOpera Full support 60Safari No support NoWebView Android Full support 73Chrome Android Full support 73Edge Mobile No support NoFirefox Android Full support 67Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support Yesnodejs No support No

Legend

Full support  
Full support
No support  
No support

相关链接