Parsing repeated structured text
Extracting every occurrence while retaining positional and capture-group information.
JavaScript · Function
String.prototype.matchAll() returns an iterator over every match of a pattern in a string, including capture groups. Consume it with standard iteration tools such as for...of or Array.from().
Call matchAll() on a string with a regular expression to obtain an iterator over every match. Each yielded array follows the shape of RegExp.prototype.exec(), so it contains the complete match, capture groups, and related match properties; consume it with for...of, spreading, or Array.from().
str.matchAll(regexp)| Name | Type | Description |
|---|---|---|
regexp | RegExp | object | A regular expression, or an object implementing Symbol.matchAll. A non-RegExp value without that method is converted with new RegExp(value, "g"). |
An iterable iterator of match arrays, or an empty iterator when no matches are found.
RegExp.prototype.exec() with a global pattern.Symbol.matchAll method.Symbol.matchAll method.g flag; otherwise the call throws a TypeError.Symbol.matchAll method.const text = "Alice: 42, Bob: 37";
const pattern = /(\w+): (\d+)/g;
for (const match of text.matchAll(pattern)) {
const [, name, score] = match;
console.log(`${name} scored ${score}`);
}Iterates over every match and reads the full match plus its two captured groups.
Extracting every occurrence while retaining positional and capture-group information.
Processing matches one at a time without writing an explicit exec() loop.
Collecting all match arrays for later transformation with Array.from().
String.prototype.matchAll() return?It returns an iterator containing every match, including capture groups. Each yielded value has the same shape as the array returned by RegExp.prototype.exec().
Follow-up: What happens when the pattern has no matches? The iterator is empty, so consuming it produces no match arrays.
g flag required?A regular-expression argument must have the global g flag. Without it, matchAll() throws a TypeError.
Follow-up: Can a non-RegExp object be passed? Yes, if it defines Symbol.matchAll; that method supplies the returned iterator.
matchAll() support custom matching behavior?The method delegates matching to the argument's Symbol.matchAll method after validating the regular expression's global flag. This allows custom matcher objects to participate in the operation.
Follow-up: What is the practical benefit over a manual exec() loop? The iterator works directly with for...of, spread syntax, and Array.from().
RegExp.prototype.exec()RegExp.prototype[Symbol.matchAll]()Symbol.matchAllString.prototype.match()