views:

51

answers:

1

Possible Duplicate:
Javascript regex returning true.. then false.. then true.. etc

var r = /\d/g;
var a = r.test("1"); // will be true
var b = r.test("1"); // will be false
console.log(a == b); // will be false

Please explain to me why the result of r.test("1") alternates with each call?

I was able to work around the issue I was having by removing the g modifier. However I would still like to understand why this happens.

+4  A: 

When you're using /g, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.

(This is a duplicate of http://stackoverflow.com/questions/2630418/)

pkh
thank you! I found some further details explaining that .test is basically shorthand for .exec() != null, and it is .exec() which stores the lastIndex for the next call.(http://www.regular-expressions.info/javascript.html)What is strange is that even when given different strings for each call, the same occurs. Does the lastIndex not reset if it is called on a different string?
Dennis George
No, because `lastIndex` is a property of the regex, not the string. In Perl, by contrast, it's associated with the string (the `pos` property), while in Java it's maintained by Matcher object. `lastIndex` is a source of much frustration: http://blog.stevenlevithan.com/archives/fixing-javascript-regexp
Alan Moore