matchAll()
method returns an iterator of all results matching a
string
against a
regular expression
,包括
capturing groups
.
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
A regular expression object.
If a non-
RegExp
object
obj
is passed, it is implicitly converted to a
RegExp
by using
new RegExp(
obj
)
.
RegExp
object must have the
/g
flag, otherwise a
TypeError
will be thrown.
An iterator (which is not a restartable iterable).
Prior to the addition of
matchAll
to JavaScript, it was possible to use calls to
regexp.exec
(and regexes with the
/g
flag) in a loop to obtain all the matches:
const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;
while ((match = regexp.exec(str)) !== null) {
console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."
}
With
matchAll
available, you can avoid the
while
loop and
exec
with
g
.
Instead, by using
matchAll
, you get an iterator to use with the more convenient
for...of
,
array spread
, or
Array.from()
constructs:
const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
const matches = str.matchAll(regexp);
for (const match of matches) {
console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."
// matches iterator is exhausted after the for..of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), m => m[0]);
// Array [ "football", "foosball" ]
matchAll
will throw an exception if the
g
flag is missing.
const regexp = RegExp('[a-c]','');
const str = 'abc';
str.matchAll(regexp);
// TypeError
matchAll
internally makes a clone of the
regexp
—so, unlike
regexp.exec()
,
lastIndex
does not change as the string is scanned.
const regexp = RegExp('[a-c]','g');
regexp.lastIndex = 1;
const str = 'abc';
Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`);
// Array [ "1 b", "1 c" ]
Another compelling reason for
matchAll
is the improved access to capture groups.
Capture groups are ignored when using
match()
with the global
/g
flag:
let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; str.match(regexp); // Array ['test1', 'test2']
使用
matchAll
, you can access capture groups easily:
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]
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'String.prototype.matchAll' in that specification. |
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.
更新 GitHub 上的兼容性数据| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
matchAll
|
Chrome 73 | Edge 79 | Firefox 67 | IE No | Opera 60 | Safari 13 | WebView Android 73 | Chrome Android 73 | Firefox Android 67 | Opera Android 52 | Safari iOS 13 | Samsung Internet Android No | nodejs 12.0.0 |
完整支持
不支持
String.prototype.match()
RegExp
RegExp.prototype.exec()
RegExp.prototype.test()
String
String.fromCharCode()
String.fromCodePoint()
String.prototype.anchor()
String.prototype.big()
String.prototype.blink()
String.prototype.bold()
String.prototype.charAt()
String.prototype.charCodeAt()
String.prototype.codePointAt()
String.prototype.concat()
String.prototype.endsWith()
String.prototype.fixed()
String.prototype.fontcolor()
String.prototype.fontsize()
String.prototype.includes()
String.prototype.indexOf()
String.prototype.italics()
String.prototype.lastIndexOf()
String.prototype.link()
String.prototype.localeCompare()
String.prototype.match()
String.prototype.matchAll()
String.prototype.normalize()
String.prototype.padEnd()
String.prototype.padStart()
String.prototype.repeat()
String.prototype.replace()
String.prototype.replaceAll()
String.prototype.search()
String.prototype.slice()
String.prototype.small()
String.prototype.split()
String.prototype.startsWith()
String.prototype.strike()
String.prototype.sub()
String.prototype.substr()
String.prototype.substring()
String.prototype.sup()
String.prototype.toLocaleLowerCase()
String.prototype.toLocaleUpperCase()
String.prototype.toLowerCase()
String.prototype.toSource()
String.prototype.toString()
String.prototype.toUpperCase()
String.prototype.trim()
String.prototype.trimEnd()
String.prototype.trimStart()
String.prototype.valueOf()
String.prototype[@@iterator]()
String.raw()
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()