Created
March 16, 2013 23:11
-
-
Save johndyer/5178734 to your computer and use it in GitHub Desktop.
Why RegExp.lastIndex is really, really important
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
var r = /love/gi, | |
s = 'i love you', | |
a = [s,s,s]; | |
for (var i=0,il=a.length; i<il; i++) { | |
console.log(r.test(a[i])); | |
} | |
/* | |
RESULTS: | |
true | |
false -- whaaaaa? | |
true | |
*/ | |
for (var i=0,il=a.length; i<il; i++) { | |
r.lastIndex = 0; | |
console.log(r.test(a[i])); | |
} | |
/* | |
RESULTS: | |
true | |
true -- much better! | |
true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment