Can anyone explain why the alert()
in the following JavaScript code is firing? It appears to be a bug in the RegExp.test()
method which reverses its previous decision each time you run the method. I'm using IE7.
I've found a replacement that appears solid, using the string.search(regex)
method instead. But, I'm curious whether anyone knows something about this.
var styleHasWidthRegex = /\bwidth\s*\:/ig;
var styleText = "WIDTH: 350px";
var result1 = styleHasWidthRegex.test(styleText);
var result2 = !styleHasWidthRegex.test(styleText);
if (result1 == result2) {
alert("This should never happen!");
}
JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
test() The test() method executes a search for a match between a regular expression and a specified string.
The " g " flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global (" g ") and sticky (" y ") will ignore the global flag and perform sticky matches. You cannot change this property directly.
Your regex has the global (g
) flag set. Every time it is executed, it'll update an internal index (the lastIndex property) specifying where it left off, and begin searching at that point the next time through.
Of course, you don't really want that - you want it to start at the beginning every time. So ditch the g
flag.
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