19

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!");
  }
John Fisher
  • 22,355
  • 2
  • 39
  • 64

2 Answers2

46

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

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
0

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

Dmitri Farkov
  • 9,133
  • 1
  • 29
  • 45