Encapsulated into a utility function:
const regexExecAll = (str: string, regex: RegExp) => {
let lastMatch: RegExpExecArray | null;
const matches: RegExpExecArray[] = [];
while ((lastMatch = regex.exec(str))) {
matches.push(lastMatch);
if (!regex.global) break;
}
return matches;
};
Usage:
const matches = regexExecAll("a a a", /(a)/g);
console.log(matches);
Output:
[
[ 'a', 'a', index: 0, input: 'a a a', groups: undefined ],
[ 'a', 'a', index: 2, input: 'a a a', groups: undefined ],
[ 'a', 'a', index: 4, input: 'a a a', groups: undefined ]
]