Skip to content

String.prototype.matchAll(): every regex match (ES2020)

  • What String.prototype.matchAll() returns and what each match object contains.
  • Why it requires the g flag, and what happens when you pass a string.
  • How the iterator behaves: lazy, one-shot, and independent of the regex’s lastIndex.
  • How to turn matches into records with named groups and ES2025 iterator helpers.
  • When match(), exec(), replace() or test() is the better choice.

TL;DR: str.matchAll(regexp) returns an iterator that yields one match object per match of a global regular expression. Each object is the same array exec() returns: the full match, the capture groups, index, input and groups. It throws a TypeError if a RegExp argument lacks the g flag.

It was added in ECMAScript 2020 and works in every current browser and server runtime (see Compatibility).

OrdersPortal support emails mention order numbers, and the team needs each number with its digits and position. Before ES2020 there were two options, and neither was good:

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23 unless a sample says otherwise.

const email = 'Please merge ORD-1042 and ORD-1077 into one shipment.';
const orderRef = /ORD-(\d+)/g;
// match() with the g flag returns only the full matches: the groups are lost.
console.log(email.match(orderRef)); // [ 'ORD-1042', 'ORD-1077' ]
// Before ES2020: an exec() loop that depends on the regex's lastIndex state.
let m;
while ((m = orderRef.exec(email)) !== null) {
console.log(m[0], m[1], m.index);
}
// ES2020: one match object per match, with groups and index.
for (const match of email.matchAll(orderRef)) {
console.log(match[0], match[1], match.index);
}

Output:

[ 'ORD-1042', 'ORD-1077' ]
ORD-1042 1042 13
ORD-1077 1077 26
ORD-1042 1042 13
ORD-1077 1077 26

The exec() loop works, but it mutates orderRef.lastIndex. If the loop exits early (a break, a thrown error), the next use of the same regex starts in the middle of the string. A regex without g makes the loop run forever. matchAll removes both hazards.

// Fragment: signature
const iterator = str.matchAll(regexp);

In the specification, String.prototype.matchAll does little itself:

  • If the argument is a regular expression, it reads its flags and throws a TypeError unless they contain g.
  • If the argument has a Symbol.matchAll method (every RegExp does), it calls it. Otherwise it converts the argument to a string and creates new RegExp(argument, 'g').
  • RegExp.prototype[Symbol.matchAll] clones the regex (through its species constructor, with the same flags), copies the original’s lastIndex to the clone, and returns a β€œRegExp String Iterator” that calls exec on the clone each time you ask for the next value.

That design explains the observable behavior:

const text = 'ORD-1042 x2, ORD-1077 x1';
try {
text.matchAll(/ORD-\d+/); // no g flag
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}
// A string argument becomes new RegExp(string, 'g'): "." is a regex wildcard here.
console.log([...'v1.2 v1x2'.matchAll('1.2')].map((m) => m[0])); // [ '1.2', '1x2' ]
// The result is a one-shot iterator.
const it = text.matchAll(/ORD-\d+/g);
console.log(Object.prototype.toString.call(it)); // [object RegExp String Iterator]
console.log([...it].length, [...it].length); // 2 0
// The original regex is cloned: its lastIndex is read once but never changed.
const re = /ORD-\d+/g;
re.lastIndex = 5;
console.log([...text.matchAll(re)].map((m) => m[0]), re.lastIndex); // [ 'ORD-1077' ] 5
// Empty matches do not loop forever: the iterator advances one position.
console.log([...'ab'.matchAll(/x*/g)].map((m) => m.index)); // [ 0, 1, 2 ]
// No match: the iterator is simply empty (match() would return null).
console.log([...text.matchAll(/RET-\d+/g)], text.match(/RET-\d+/g)); // [] null

Output:

TypeError - String.prototype.matchAll called with a non-global RegExp argument
[ '1.2', '1x2' ]
[object RegExp String Iterator]
2 0
[ 'ORD-1077' ] 5
[ 0, 1, 2 ]
[] null

The iterator is lazy: each next() runs one exec, so you can stop early without scanning the rest of the input.

The iterator inherits from Iterator.prototype, so the ES2025 iterator helpers (map, filter, take, toArray, …) work on it directly. Each match object also gets an indices array when the regex has the d flag (ES2022):

// The d flag (ES2022) adds start/end offsets for every group.
const [match] = 'Ship ORD-1042 today'.matchAll(/ORD-(?<num>\d+)/dg);
console.log(match.indices[0], match.indices.groups.num); // [ 5, 13 ] [ 9, 13 ]

OrdersPortal turns the line items in a support email into records. Named groups make the result self-describing, and iterator helpers map the matches without building an intermediate array (needs Node.js 22, Chrome 122, Firefox 131 or Safari 18.4 for the helpers):

// parse-notes.mjs - pull structured order lines out of OrdersPortal support emails.
const LINE_ITEM = /(?<orderId>ORD-\d{4})\s+(?<sku>[A-Z]{3}-\d{3})\s+x(?<qty>\d+)/g;
export function parseLineItems(text) {
return text
.matchAll(LINE_ITEM)
// Iterator helpers (ES2025): map lazily, then collect.
.map(({ groups, index }) => ({ ...groups, qty: Number(groups.qty), at: index }))
.toArray();
}
const email = `Hi team,
please replace these items:
ORD-1042 MUG-001 x2
ORD-1042 BNS-104 x1
ORD-1077 MUG-001 x3
Thanks!`;
console.table(parseLineItems(email));
// Lazy: stop after the first match without scanning the rest of the text.
const first = email.matchAll(LINE_ITEM).next().value;
console.log(first.groups.orderId, first.index);

Output:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”
β”‚ (index) β”‚ orderId β”‚ sku β”‚ qty β”‚ at β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€
β”‚ 0 β”‚ 'ORD-1042' β”‚ 'MUG-001' β”‚ 2 β”‚ 39 β”‚
β”‚ 1 β”‚ 'ORD-1042' β”‚ 'BNS-104' β”‚ 1 β”‚ 61 β”‚
β”‚ 2 β”‚ 'ORD-1077' β”‚ 'MUG-001' β”‚ 3 β”‚ 83 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜
ORD-1042 39

Sharing the module-level LINE_ITEM regex is safe here because matchAll clones it; the same code with an exec() loop would leave LINE_ITEM.lastIndex pointing into the previous email. On runtimes without iterator helpers, write Array.from(text.matchAll(LINE_ITEM), mapFn).

  • Forgetting the g flag. str.matchAll(/x/) throws a TypeError. Add g.

  • Iterating twice. The iterator is exhausted after one pass; the second [...it] is []. Spread it into an array once if you need it again.

  • Passing user text as a pattern. A string argument is compiled as a regex, so . and ( are special and a malformed pattern throws a SyntaxError. Escape it with RegExp.escape() (ES2025):

    // Needs Node.js 24 (RegExp.escape, ES2025).
    const userInput = 'MUG-001 (blue)';
    const re = new RegExp(RegExp.escape(userInput), 'gi');
    const notes = 'Swap mug-001 (BLUE) for MUG-001 (blue) on ORD-1042';
    console.log([...notes.matchAll(re)].map((m) => `${m[0]} @${m.index}`));

    Output (Node.js 24.22): [ 'mug-001 (BLUE) @5', 'MUG-001 (blue) @24' ]. On Node.js 22 RegExp.escape is not available; for literal text, includes or indexOf in a loop needs no regex at all.

  • Reusing a global regex with a stale lastIndex. matchAll starts where the original’s lastIndex points. After test() or exec() on the same regex, reset it to 0.

  • Collecting everything from huge input. [...str.matchAll(re)] holds every match array in memory. Iterate with for...of and process as you go.

  • Catastrophic backtracking. matchAll runs the regex repeatedly over the whole string, so a pattern with nested quantifiers such as (a+)+$ can take exponential time on hostile input. Keep patterns simple and bound the input size.

  • Missing the u or v flag for emoji. Without it, . matches half of a surrogate pair. Add u (or v) when patterns touch non-BMP characters.

Need Use
Every match with groups and positions str.matchAll(/re/g)
Only the matched strings str.match(/re/g) (returns null when nothing matches)
The first match with groups str.match(/re/) or re.exec(str)
Yes or no re.test(str), or includes() for plain text
Rewrite every match str.replace(/re/g, fn) or str.replaceAll(re, fn)
Split on a pattern str.split(/re/)

According to MDN’s browser compatibility data, String.prototype.matchAll is supported in Chrome 73, Edge 79, Firefox 67, Safari 13 (including iOS), Opera 60, Node.js 12.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it; core-js provides a polyfill. The iterator helpers in the realistic example need Chrome 122, Firefox 131, Safari 18.4 or Node.js 22; RegExp.escape needs Chrome 136, Firefox 134, Safari 18.2 or Node.js 24.

TypeScript: declared in lib.es2020.string.d.ts as matchAll(regexp: RegExp): RegExpStringIterator<RegExpExecArray>, so passing a string is a type error even though JavaScript accepts it. Use target or lib ES2020 or later. TypeScript does not check the g flag at compile time.

1. Why does matchAll throw for a regex without the g flag? A non-global regex means β€œfind one match”. Rather than silently treating it as global, which matchAll would have to do to return more than one result, the specification throws a TypeError so the regex and the call agree.

2. What is the difference between str.match(/re/g) and str.matchAll(/re/g)? match with g returns an array of matched strings (or null) and drops capture groups and positions. matchAll returns a lazy iterator of full match objects with groups, index and input, and an empty iterator when nothing matches.

3. Does matchAll change the regex’s lastIndex? No. It reads lastIndex to choose the starting point, then works on a clone, so the original’s lastIndex is unchanged. An exec() loop, by contrast, advances it.

4. Senior scenario: OrdersPortal must extract order IDs from a 200 MB nightly log export, and the first implementation [...log.matchAll(re)] runs out of memory. How do you redesign it? Do not load the whole file into one string. Stream it line by line (readline over a file stream in Node.js) and run matchAll per line, handling each match in a for...of loop so nothing accumulates. Keep the regex simple and anchored to the ID format to avoid backtracking, write results incrementally (to a file or a database batch), and deduplicate with a Set only if the distinct count is bounded. If IDs can span line breaks, buffer a small overlap between chunks.

  • matchAll (ES2020) yields one exec-style match object per match of a global regex, with groups, index and input.
  • It requires g, compiles strings as patterns, and works on a clone, so the original lastIndex is untouched.
  • The iterator is lazy and one-shot; use for...of for large inputs and iterator helpers or Array.from to transform.
  • Escape user input before using it as a pattern, and keep patterns safe from backtracking.