String.prototype.matchAll(): every regex match (ES2020)
What youβll learn
Section titled βWhat youβll learnβ- What
String.prototype.matchAll()returns and what each match object contains. - Why it requires the
gflag, 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()ortest()is the better choice.
Summary
Section titled βSummaryβ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).
The problem it solves
Section titled βThe problem it solvesβ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 13ORD-1077 1077 26ORD-1042 1042 13ORD-1077 1077 26The 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.
How it works
Section titled βHow it worksβ// Fragment: signatureconst iterator = str.matchAll(regexp);In the specification, String.prototype.matchAll does little itself:
- If the argument is a regular expression, it reads its
flagsand throws aTypeErrorunless they containg. - If the argument has a
Symbol.matchAllmethod (every RegExp does), it calls it. Otherwise it converts the argument to a string and createsnew RegExp(argument, 'g'). RegExp.prototype[Symbol.matchAll]clones the regex (through its species constructor, with the same flags), copies the originalβslastIndexto the clone, and returns a βRegExp String Iteratorβ that callsexecon 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)); // [] nullOutput:
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 ][] nullThe 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 ]Realistic example
Section titled βRealistic exampleβ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 x3Thanks!`;
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 39Sharing 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).
Common mistakes
Section titled βCommon mistakesβ-
Forgetting the
gflag.str.matchAll(/x/)throws aTypeError. Addg. -
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 aSyntaxError. Escape it withRegExp.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 22RegExp.escapeis not available; for literal text,includesorindexOfin a loop needs no regex at all. -
Reusing a global regex with a stale
lastIndex.matchAllstarts where the originalβslastIndexpoints. Aftertest()orexec()on the same regex, reset it to0. -
Collecting everything from huge input.
[...str.matchAll(re)]holds every match array in memory. Iterate withfor...ofand process as you go. -
Catastrophic backtracking.
matchAllruns 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
uorvflag for emoji. Without it,.matches half of a surrogate pair. Addu(orv) when patterns touch non-BMP characters.
When to use it and when not to
Section titled βWhen to use it and when not toβ| 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/) |
Compatibility
Section titled βCompatibilityβ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.
Interview questions
Section titled βInterview questionsβ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.
Key takeaways
Section titled βKey takeawaysβmatchAll(ES2020) yields oneexec-style match object per match of a global regex, with groups,indexandinput.- It requires
g, compiles strings as patterns, and works on a clone, so the originallastIndexis untouched. - The iterator is lazy and one-shot; use
for...offor large inputs and iterator helpers orArray.fromto transform. - Escape user input before using it as a pattern, and keep patterns safe from backtracking.
Related pages
Section titled βRelated pagesβ- RegExp features: named groups, lookbehind and other regex additions.
- Iterators: the protocol
matchAllreturns. - forβ¦of: the loop used to consume matches.
- Unicode support: the
uflag and surrogate pairs. - String.prototype.includes(): plain substring checks without a regex.
- Regular expressions: the basics.
- JavaScript interview questions
Official references
Section titled βOfficial referencesβ- ECMAScript Language Specification,
String.prototype.matchAllandRegExp.prototype[Symbol.matchAll](current draft) - ECMAScript 2020 Language Specification (ECMA-262, 11th edition),
String.prototype.matchAll - TC39 proposal: String.prototype.matchAll
- MDN: String.prototype.matchAll()
- MDN: RegExp.escape()
- MDN: Iterator.prototype.map()
- TypeScript 6.0.3:
lib.es2020.string.d.ts