0

const reg = new RegExp("c6", 'gi')
console.log(reg.test("c6289"));
console.log(reg.test("c6289"));

Why does this happen?

  • 2
    it's how .test works - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test – Bravo Jul 30 '21 at 05:05
  • 1
    This is because of the `g` flag. see specifically [this section](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag) – DecPK Jul 30 '21 at 05:08
  • Does this answer your question? [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) – Sebastian Simon Jul 30 '21 at 05:31

1 Answers1

1

For global flag lastIndex is set for each test when using test()

More details here

Using test() on a regex with the "global" flag

When a regex has the global flag set, test() will advance the lastIndex of the regex.

Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time test() returns true.

Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!

When test() returns false, the calling regex's lastIndex property will reset to 0.

mk23
  • 1,257
  • 1
  • 12
  • 25