The JavaScript string.matchAll() method
The matchAll() method returns an iterator of all matches of a global regex, each with its capture groups. [...str.matchAll(/(\d+)/g)] gives every match plus its groups. It's better than match() when you need all matches and their groups. The regex must have the g flag.
Overview
matchAll() fills a gap in match(): when you use match() with the global g flag, it returns just the matched strings and throws away the capture groups. matchAll() keeps everything — it returns an iterator where each item is a full match object, with the whole match at index 0, then each captured group, plus the index and named groups.
Because it returns an iterator, you typically consume it with a for...of loop, or spread it into an array with [...str.matchAll(re)] to use array methods. Each iteration gives you a match with its groups, which is exactly what you need to extract structured data — pulling the key and value out of each key=value pair, or the parts of every date in a string.
One requirement: the regex must have the g flag, or matchAll() throws a TypeError (it's a guard so the name and behavior agree). If you only need the matched strings without groups, str.match(/.../g) is simpler; if you only need the first match with its groups, plain match() (no g) does that. Reach for matchAll() when you want all matches with their groups.
Syntax
for (const match of str.matchAll(regexp)) {
match[0] // the full match
match[1] // first capture group
match.index
}
const all = [...str.matchAll(/(\w+)=(\w+)/g)];
Parameters
The string.matchAll() method accepts the following parameters.
| Parameter | Description |
|---|---|
regexp |
A global (/.../g) regular expression. A non-global regex throws a TypeError. |
Example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
const text = 'width=200 height=100 depth=50';
const lines = [];
for (const m of text.matchAll(/(\w+)=(\d+)/g)) {
lines.push(m[1] + ' is ' + m[2]);
}
document.getElementById('out').textContent = lines.join('\n');
// width is 200 / height is 100 / depth is 50
</script>
Best practices
- Use
matchAll()when you need all matches and their capture groups together. - Include the
gflag, or it throws aTypeError. - Consume it with for...of, or spread into an array with
[...str.matchAll(re)]. - For just the matched strings,
str.match(/.../g)is simpler; for one match with groups, plain match().
Frequently asked questions
What is the difference between match() and matchAll()?
/g returns only the matched strings (no groups); matchAll() returns an iterator of every match with its capture groups.Why does matchAll() throw a TypeError?
matchAll() requires the g flag.How do I loop over all matches with groups?
for (const m of str.matchAll(/.../g)) { ... }, reading m[0], m[1], etc.How do I turn matchAll() into an array?
const matches = [...str.matchAll(re)].