Skip to content

Instantly share code, notes, and snippets.

@slevithan
Created August 24, 2012 00:36
Show Gist options
  • Save slevithan/3444018 to your computer and use it in GitHub Desktop.
Save slevithan/3444018 to your computer and use it in GitHub Desktop.
A comparison of how to safely iterate over all regex matches, when accepting an arbitrary regex.
// Using native JavaScript...
function getMatches(str, regex) {
var matches = [];
var match;
if (regex.global) {
regex.lastIndex = 0;
} else {
regex = new RegExp(regex.source, 'g' +
(regex.ignoreCase ? 'i' : '') +
(regex.multiline ? 'm' : '') +
(regex.sticky ? 'y' : ''));
}
while (match = regex.exec(str)) {
// If you want to use regex.lastIndex in this loop, you'd need more
// code here to fix IE < 9
matches.push(match);
if (regex.lastIndex === match.index) {
regex.lastIndex++;
}
}
return matches;
}
// Using XRegExp...
function getMatches(str, regex) {
return XRegExp.forEach(str, regex, function(match) {
this.push(match);
}, []);
}
@mathiasbynens
Copy link

So you’re using XRegExp.forEach as if it was reduce? Cool :)

@slevithan
Copy link
Author

@mathiasbynens, XRegExp.forEach always returns its callback's context (this). You can set the context either by using a bind method or, as I did in this example, via the fourth argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment