matchAll()
is a new method added to String prototype. It works similar to Regular Expression. The method returns an iterator. The iterator returns all matches one after other.
const regExp = /world/g;
const str = "This world is a beautiful world";
const iterator = str.matchAll(regExp);
for (const match of iterator) {
console.log(match);
}
The match
will be an object containing information like the input string and position of the match.
Here we used for...of
to loop through the iterator. We can also use array spread
and Array.from()
. And for the regular expression, the ending /g
is mandatory. Otherwise, .matchAll()
throws TypeError
.