Created
January 5, 2019 07:10
-
-
Save agusputra/a56ab2438827389993633037848d0d09 to your computer and use it in GitHub Desktop.
Get all matches when using regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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