I do not understand why the javascript RegExp.test()
method do no return the same result every time I call it.
Given the following javascript variables
var opener = '<span[^>]*>';
var regexo = new RegExp('^'+opener+'$', "g");
I do the following:
alert(regexo.test('<span class="outer">')); // true
alert(regexo.test('<span class="inner">')); // false
alert(regexo.test('<span class="inner">')); // true
I tested it in Firefox 24.0 and IE8 with the same strange result.
Why is the result true, false, true
instead of true, true, true
?
That's because you use the g
flag. It turns the regexp object into an iterator, whose state changes with each call.
You don't need the g
flag here, so just remove it :
var regexo = new RegExp('^'+opener+'$');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With