JavaScript Reference ยท String
String.prototype.matchAll()
Reference for JavaScript String.prototype.matchAll(): iterate over every regular expression match with capture groups and positions, and why the g flag is required.
The matchAll() method finds every match of a regular expression and gives them back through an iterator. Each item is a full match result, the same shape exec() returns: the matched text, the capture groups, the index and any named groups.
This fills the gap left by match(), which drops groups and positions when you use the g flag. It also replaces the old while ((m = re.exec(text))) loop, which needs care with lastIndex.
for (const m of "a1b2".matchAll(/\d/g)) { console.log(m[0], m.index); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.matchAll(regexp)
| Name | Description |
|---|---|
regexp |
A regular expression with the g flag. If it has no g, a TypeError is thrown. A non-regex argument is passed to new RegExp(value, "g"), so strings become patterns. |
Return value: an iterator (also iterable) of match arrays. Each array has the matched text at 0, capture groups at 1 and up, and the properties index, input and groups. If nothing matches, the iterator is simply empty; there is no null.
Exceptions: a TypeError for a regular expression without the g flag.
Usage notes
- The
gflag is mandatory for regex arguments. The error is deliberate: without it, you would silently get only one match. - The iterator is single-use. After one pass (or after spreading it), it is exhausted. Call
matchAll()again, or turn it into an array first withArray.from()or spread. - Your regex is not modified.
matchAll()works on a clone, so the original'slastIndexstays where it was, and it is safe to reuse a shared constant. - It is lazy. Matches are found as you iterate, so you can
breakout of afor...ofloop early. - Groups and indexes are the reason to prefer it over
match(/.../g). To get only the matched strings,match()withgis simpler. - Strings become patterns, as with
match()."a.b.c".matchAll(".")matches every character, not every dot. - Replacing instead of reading?
replace()with a function callback also receives each match with its groups. - Empty matches are allowed and advance by one position, so patterns that can match nothing do not loop forever.
- Need positions of group parts? Add the
dflag to getindiceson each match.
Browser support
matchAll() is part of ES2020 and works in all current browsers. Very old browsers lack it, so check a compatibility table if you support them.