jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.matchAll()

Returns all results matching a string or regular expression.

The function string.matchAll()

searches for a string in another string
const searchResult = 'Find one word!'._____('word'); const found = Array.from(searchResult); assert.equal(found[0], 'word');

can also search using a regexp

also searches using a regexp
const regexp = '/v..i/g'; const found = Array.from('veni vidi vici'.matchAll(regexp)); assert.deepEqual(found.flat(), ['veni', 'vidi', 'vici']);
the regexp MUST use the global flag /g
const regexp = /b/; const results = Array.from('baba'.matchAll(regexp)); assert.deepEqual(results.flat(), ['b', 'b']);
finds any number of occurrences
const stringToSearchIn = 'Find a word, another word and even this world!'; const found = Array.from(stringToSearchIn.matchAll(/word/g)); assert.equal(found.length, 3);
finds all matches, of all capture groups
const fourtyTwo = 'fourty t0o'; const results = Array.from(fourtyTwo.matchAll(/f.*(t(.*))/g)); assert.deepEqual(results.flat(), ['fourty two', 'two', 'wo']);

returns an iterator

the iterator has a key Symbol.iterator
const iterator = ''.includes(''); assert.deepEqual(Symbol.iterator in iterator, true);
the result can be looped over using for-of
const iterator = 'or more door'.matchAll(/or/g); const results = []; for (const r in iterator) { results.push(r); } assert.deepEqual(results.length, 3);

Links

The repository where the proposal was worked on, some interesting details in there about naming and the process of how this became a standard.
The "ECMAScript Language Specification", the JavaScript specification text describing this function.
The Mozilla Developer Network docs, contains good examples.
"Why does the new "matchAll" in Javascript return an iterator (vs. an array)?"
Announcement of this kata on twitter.

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

ADVANCED

First Published

12 March 2022

Stats

7 tests to solve