Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.matchAll — a match iterator with capture groups

String.prototype.matchAll returns an iterator over regular-expression matches, including capture groups and positions. For an ordinary RegExp it requires the g flag and leaves the original pattern's lastIndex unchanged.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

string.matchAll(regexp)

String.prototype.matchAll lets you iterate over pattern matches in text. With standard RegExp behavior, it returns a lazy iterator: each step yields an array whose [0] contains the complete match and whose [1], [2], and later elements contain capture groups. An unmatched optional group is undefined. The index property gives the position in UTF-16 code units, input contains the input text, and groups exposes named groups when present.

If the argument is recognized as a regular expression, matchAll checks for the g flag before looking up Symbol.matchAll. If the flag is missing, the call throws TypeError. The lookup includes inherited properties: if the value found is callable, matchAll calls it and returns its result. If the property is missing or its value is undefined or null, matchAll creates a RegExp from the argument with the g flag. In this fallback, a string argument is treated as a regular-expression pattern, not literal text. Any other non-callable Symbol.matchAll value causes a TypeError.

The standard RegExp implementation copies the pattern and sets the new matcher's initial lastIndex to the result of applying ToLength to the original's lastIndex. For example, -1 becomes 0 and 2.9 becomes 2. The original's lastIndex remains unchanged. Do not assume that searching always starts at zero. The iterator is single-use: once exhausted, it does not restart. No matches means an empty iteration, not null; use for...of to process results or [...iterator] to store them in an array.

Unlike match with the g flag, matchAll preserves capture groups for every match. The method belongs to ECMAScript 2020, not Web APIs. The specification alone does not establish support in a particular browser; Node 24 in a repository does not prove it either. In the target environment, availability can be checked with typeof String.prototype.matchAll === "function".

Examples

const text = "x=12 y=7";
const pattern = /([a-z])=(\d+)/g;
const matches = text.matchAll(pattern);

for (const match of matches) {
  console.log(`${match[0]} | ${match[1]} | ${match[2]} | ${match.index}`);
}
console.log(`lastIndex=${pattern.lastIndex}`);
console.log(`remaining=${[...matches].length}`);

Result

x=12 | x | 12 | 0
y=7 | y | 7 | 5
lastIndex=0
remaining=0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources