Created
August 24, 2012 00:36
-
-
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.
This file contains 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
// 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; | |
} |
This file contains 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
// Using XRegExp... | |
function getMatches(str, regex) { | |
return XRegExp.forEach(str, regex, function(match) { | |
this.push(match); | |
}, []); | |
} |
@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
So you’re using
XRegExp.forEach
as if it wasreduce
? Cool :)