If you have ES9
(Meaning if your system: Chrome, Node.js, Deno, Bun, Firefox, etc supports Ecmascript 2019 or later)
yourString.matchAll( /your-regex/g ) // dont forget the "g"
MDN Documentation
If you use NPM
You can use the official polyfill
npm install string.prototype.matchall
const matchAll = require('string.prototype.matchall')
console.log( [... matchAll('blah1 blah2',/blah/g) ] )
//[
// [ 'blah', index: 0, input: 'blah1 blah2', groups: undefined ],
// [ 'blah', index: 6, input: 'blah1 blah2', groups: undefined ]
//]
Otherwise
Here's some functionally similar copy-paste versions
// returns an array, works on super old javascript (ES3 -- 1999)
function findAll(regexPattern, sourceString) {
var output = []
var match
// auto-add global flag while keeping others as-is
var regexPatternWithGlobal = regexPattern.global ? regexPattern : RegExp(regexPattern, regexPattern.flags+"g")
while (match = regexPatternWithGlobal.exec(sourceString)) {
// store the match data
output.push(match)
// zero-length matches will end up in an infinite loop, so increment by one char after a zero-length match is found
if (match[0].length == 0) {
regexPatternWithGlobal.lastIndex += 1
}
}
return output
}
// this version returns an iterator, which is good for large results
// note: iterators require ES6 - 2015 standard
function* findAll(regexPattern, sourceString) {
var match
// auto-add global flag while keeping others as-is
const regexPatternWithGlobal = regexPattern.global ? regexPattern : RegExp(regexPattern, regexPattern.flags+"g")
while (match = regexPatternWithGlobal.exec(sourceString)) {
// store the match data
yield match
// zero-length matches will end up in an infinite loop, so increment by one char after a zero-length match is found
if (match[0].length == 0) {
regexPatternWithGlobal.lastIndex += 1
}
}
return output
}
example usage:
console.log( findAll(/blah/g,'blah1 blah2') )
outputs:
[ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]
"some string".match(/regex/g)
str.matchAll(regex)
to get all matches, including meta-info like groups. So this should be the accepted answer, since it's quite well-supported now.