Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the JavaScript RegExp.test() method behaving as a toggle? [duplicate]

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!");
  }
like image 607
John Fisher Avatar asked May 21 '09 19:05

John Fisher


People also ask

What is the purpose of RegExp method test ()?

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.

What is the function to test the matching of a text in a RegExp object in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string.

What does the G flag do regex?

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.


1 Answers

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

like image 134
Shog9 Avatar answered Oct 14 '22 09:10

Shog9