110

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.

0

1 Answer 1

177

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 Javascript regex returning true.. then false.. then true.. etc)

Sign up to request clarification or add additional context in comments.

4 Comments

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. (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?
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: blog.stevenlevithan.com/archives/fixing-javascript-regexp
waste my life debugging this weird thing ...
I took 2 days debugging a service worker that randomly cached assets based on a /../g regexp. Now it is explained why.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.