Skip to content

Instantly share code, notes, and snippets.

@agusputra
Created January 5, 2019 07:10
Show Gist options
  • Save agusputra/a56ab2438827389993633037848d0d09 to your computer and use it in GitHub Desktop.
Save agusputra/a56ab2438827389993633037848d0d09 to your computer and use it in GitHub Desktop.
Get all matches when using regex
function allMatches (regex, text) {
if (!regex.global) throw new Error('option global not set')
let matches = []
while(true) {
const match = regex.exec(text)
if (!match) break;
matches.push(match)
}
return matches
}
const matches = allMatches(/a|b|c/g, 'abcabcabc')
for(let item of matches) {
console.log(item)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment