search

String.prototype.matchAll

Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.

str.matchAll(regexp)

Parameters

Parameter Purpose
regexp Global RegExp; strings are coerced to new RegExp(value, 'g')
returns Iterator yielding one match array per hit

Examples

console.log([...'a1 b2'.matchAll(/([a-z])(\d)/g)].map(m => m[0]));

Prints [ 'a1', 'b2' ]

for (const m of 'a1 b2'.matchAll(/([a-z])(\d)/g)) console.log(m[1], m[2]);

Prints 'a 1' then 'b 2' on two lines

console.log([...'abc'.matchAll(/z/g)]);

Prints [] (no matches)

try { 'abc'.matchAll(/a/); } catch (e) { console.log(e.name); }

Prints 'TypeError' (non-global RegExp)

Gotcha

Argument must be a global RegExp or the call throws. Returns an iterator, not an array — spread or Array.from() it if you need indexing.

Related methods

← All JS string methods · JS array methods