jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.matchAll() in depth

Returns all results matching a string or regular expression.

The function string.matchAll() in depth

matchAll() is lazy
// ????
check all array`s object properties
const str = 'test'; const regexp = /test/g; const array = [...str.matchAll(regexp)]; const expectedArr = ['test']; expectedArr.groups = undefined; expectedArr.index = 0; expectedArr.input = 'test'; assert.deepEqual(array[0], expectedArr);

is intentionally generic, it does not require that its this value be a String object

pass it an array, it gets casted to a string
const results = Array.from(String.prototype.matchAll.bind(['1', '2', '3', '10'])(/1/g)); assert.deepStrictEqual(results.flat(), ['1', '1']);
an object
const results = Array.from(String.prototype.matchAll.bind({})(/OBJECT/gi)) assert.deepStrictEqual(results.flat(), ['object', 'Object']);

returns an Array with custom properties

it is an array
const matchAll = () => { const str = 'test'; const regexp = /test/g; const iter = str.matchAll(regexp); const {value} = iter.next(); return value; }; assert(Array.isArray(matchAll()));
but it is not a pure array
const matchAll = () => { const str = 'test'; const regexp = /test/g; const iter = str.matchAll(regexp); const {value} = iter.next(); return value; }; // assert.notDeepEqual(matchAll(), ['test']);
it must be converted to be a pure array (without custom properties)
const matchAll = () => { const str = 'test'; const regexp = /test/g; const iter = str.matchAll(regexp); const {value} = iter.next(); return value; }; assert.deepEqual(Array.from(matchAll()), ['test']);
one property is groups
const matchAll = () => { const str = 'test'; const regexp = /test/g; const iter = str.matchAll(regexp); const {value} = iter.next(); return value; }; assert(matchAll().hasOwnProperty('groups'));
another property is index, which is the position of the first capture group
const matchAll = () => { const str = 'test'; const regexp = /test/g; const iter = str.matchAll(regexp); const {value} = iter.next(); return value; }; assert.equal(matchAll().index, 0);
another property is input, which is the actual string to search in
// const {value} = 'test'.matchAll(/test/).next(); // assert.equal(value.input, 'test');

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

ADVANCED

Stats

10 tests to solve