16

Open up a browser console and execute the following code:

var foo = /foo/g;

Then,

foo.test("foo") // true

Then,

foo.test("foo") // false

If you continue to execute foo.test("foo"), you will see alternating true/false responses as if the var foo is actually being modified.

Anyone know why this is happening?

Gregory Mazurek
  • 221
  • 1
  • 10

2 Answers2

19

Yes, that's how .test() and .exec() work when the regex is g global. They start at the end of the last match.

You can observe the current last index on the regular expression object using the .lastIndex property.

It's a writeable property, so you can reset it to 0 when/if you need. When the regex is run without finding a match, it automatically resets to 0.

the system
  • 9,244
  • 40
  • 46
2

The regex keeps the position of the last test. This allows searching of long strings. You can reset this by setting lastIndex = 0;

QuentinUK
  • 2,997
  • 21
  • 20