Created
March 17, 2023 13:03
-
-
Save wosephjeber/4b20cfe554515230930e608a454f34e5 to your computer and use it in GitHub Desktop.
Get all regex matches in a string
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 getAllRegexMatches(regex: RegExp, string: string) { | |
if (regex.constructor !== RegExp) { | |
throw new Error('not RegExp'); | |
} | |
const matches = []; | |
let match = regex.exec(string); | |
if (regex.global) { | |
while (match) { | |
matches.push(match); | |
match = regex.exec(string); | |
} | |
} else if (match) { | |
matches.push(match); | |
} | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment