Skip to content

Instantly share code, notes, and snippets.

@wosephjeber
Created March 17, 2023 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wosephjeber/4b20cfe554515230930e608a454f34e5 to your computer and use it in GitHub Desktop.
Save wosephjeber/4b20cfe554515230930e608a454f34e5 to your computer and use it in GitHub Desktop.
Get all regex matches in a string
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