matchAll method
The matchAll method returns all
matches with
regular expression
as an iterable object,
each element of which contains an array
of found and its capturing groups. The
method can only be called with the
g modifier. If there are no
matches, it will return null.
Syntax
javascriptstring.matchAll(regular expression);
Example
Let's get all matches and loop through them:
javascriptlet str = '12 34 56';
let matches = str.matchAll(/(\d)(\d)/g);
for (let match of matches) {
console.log(match);
}
The code execution result:
javascript[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Example
Let's convert the iterable object to a regular array:
javascriptlet str = '12 34 56';
let matches = str.matchAll(/(\d)(\d)/g);
let res = Array.from(matches);
console.log(res);
The code execution result:
javascript[
[12, 1, 2],
[34, 3, 4],
[56, 5, 6]
]