105

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.

Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
Dennis George
  • 1,495
  • 2
  • 10
  • 18

1 Answers1

168

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)

Community
  • 1
  • 1
pkh
  • 3,639
  • 1
  • 23
  • 18
  • 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 May 17 '10 at 17:52
  • 2
    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 May 18 '10 at 01:49
  • 14
    waste my life debugging this weird thing ... – Hasan Daghash Feb 27 '19 at 11:02
  • 1
    I took 2 days debugging a service worker that randomly cached assets based on a /../g regexp. Now it is explained why. – Eduardo Poço Feb 10 '21 at 15:11