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
String.prototype.match
Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.
String.prototype[Symbol.iterator]
Returns an iterator that yields the string's Unicode code points as single-character strings, correctly handling surrogate pairs. This is what powers for...of loops and spread over strings.
String.prototype.indexOf
Returns the index of the first occurrence of searchValue within the string, or -1 if not found. Search is case-sensitive and starts from fromIndex (default 0).
String.prototype.includes
Returns true if searchString appears anywhere in the string, otherwise false. Added in ES2015 as a cleaner boolean alternative to indexOf() !== -1.