views:

290

answers:

2

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!");
  }
+13  A: 

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.

See also: Inconsistent javascript logic behavior

Shog9
Thanks for making sense out of that.
John Fisher
very interesting. I didn't know that.
andi
no problem, John. Took me a while to get it the first time i saw it too!
Shog9
A: 

In this scenario, you should be needing a global tag anyways, since in css declarations a property should only be declared once.

Dmitri Farkov