String .matchAll() in JavaScript

Last updated on 12 Feb, 2021

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) {

The match will be an object containing information like the input string and position of the match.

Output: .matchAll()

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.

--- ○ ---
Joby Joseph
Web Architect