String.prototype.matchAll
Returns every match together with its groups.
Available since: ES2020
Syntax
str.matchAll(regexp)Parameters
| Parameter | Type | Description |
|---|---|---|
| regexp | RegExp | A regular expression; it must have the g flag. |
Return value
IteratorAn iterator of matches, each with groups and a position.
Examples
All key=value pairs:
const text = 'a=1, b=2, c=3';
for (const match of text.matchAll(/(\w)=(\d)/g)) {
console.log(match[1], match[2], match.index);
}Output:
a 1 0
b 2 5
c 3 10Matches into an object via named groups:
const text = 'width=300 height=200';
const entries = [...text.matchAll(/(?<key>\w+)=(?<value>\d+)/g)].map((m) => [m.groups.key, Number(m.groups.value)]);
console.log(Object.fromEntries(entries));Output:
{
"width": 300,
"height": 200
}Notes
Without the g flag the method throws a TypeError. Unlike match() with g, it keeps the groups of every match.
See also
- String.prototype.match — Finds matches of a regular expression.
- RegExp.prototype.exec — Finds a match and returns the details: groups and position.
- Named capture groups — Named groups — parts of a match with readable names.
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.