Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active April 1, 2024 20:26
Show Gist options
  • Save ryanmorr/915ca8898fdfef43106b24e77022ac24 to your computer and use it in GitHub Desktop.
Save ryanmorr/915ca8898fdfef43106b24e77022ac24 to your computer and use it in GitHub Desktop.
Iterate through all the matches of a regular expression and call a function
function forEachMatch(regex, str, callback) {
if (regex.global) {
regex.lastIndex = 0;
}
let i = -1, match;
while ((match = regex.exec(str))) {
callback(match, i++, str, regex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment