str.match(/regex/g)
returns all matches as an array.
If, for some mysterious reason, you need the additional information comes with exec
, as an alternative to previous answers, you could do it with a recursive function instead of a loop as follows (which also looks cooler :).
function findMatches(regex, str, matches = []) {
const res = regex.exec(str)
res && matches.push(res) && findMatches(regex, str, matches)
return matches
}
// Usage
const matches = findMatches(/regex/g, str)
as stated in the comments before, it's important to have g
at the end of regex definition to move the pointer forward in each execution.