const reg = new RegExp("c6", 'gi')
console.log(reg.test("c6289"));
console.log(reg.test("c6289"));
Why does this happen?
const reg = new RegExp("c6", 'gi')
console.log(reg.test("c6289"));
console.log(reg.test("c6289"));
Why does this happen?
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.