Possible Duplicate:
Interesting test of Javascript RegExp
Regular expression test can't decide between true and false (JavaScript)
Example of issue. When ran inline the results are as I would expect. But when stored as a variable it skips the middle span element.
// Inline RegExp
function getToggleClasses() {
var toggler = [],
elements = document.getElementsByTagName("*"),
i=0,
len = elements.length;
for (i; i < len; i++) {
if (/toggler/g.test(elements[i].className)) {
toggler.push(elements[i]);
}
}
document.getElementById('results').innerHTML += "<br />Inline: " + toggler.length;
}
// Variable
function getToggleClasses2() {
var toggler = [],
elements = document.getElementsByTagName("*"),
tester = /toggler/g,
i=0,
len = elements.length;
for (i; i < len; i++) {
if (tester.test(elements[i].className)) {
toggler.push(elements[i]);
}
}
document.getElementById('results').innerHTML += "<br />Variable: " + toggler.length;
}
Mark up:
<span class="toggler">A</span>
<span class="toggler">B</span>
<span class="toggler">C</span>
Given:
I understand there is no reason to use a RegExp to do this comparison and I also understand how great libraries such as jQuery are. I also know that the g is not needed in this case.
I can’t understand why these two methods should ever return different results.
RegExpinstances are stateful, so reusing them can cause unexpected behavior. In this particular case, it’s because the instance is global, meaning:That’s not the only difference caused by using
g, however. FromRegExp.test@ MDN:Remove the
gflag, or setlastIndexto0(thanks, @zzzzBov).