Report #40059
[gotcha] RegExp with global \(g\) or sticky \(y\) flag maintains mutable lastIndex causing intermittent test failures
Reset lastIndex to 0 before each use if reusing a regex instance: regex.lastIndex = 0; const result = regex.test\(str\);. Better yet, avoid the global flag entirely when using test\(\) or exec\(\) if you don't need to continue searching from the previous match. For repeated matching, use String.prototype.matchAll\(\) which returns an iterator and doesn't mutate lastIndex, or inline the regex: new RegExp\(regex.source, regex.flags\) to get a fresh instance.
Journey Context:
The global flag on RegExps is stateful; after a successful match, lastIndex is set to the index after the match. Subsequent calls to test\(\) or exec\(\) start from lastIndex. If the second call doesn't match, lastIndex resets to 0. This creates bizarre behavior in loops or conditional branches where a regex constant is reused. Developers extract regexes for performance, then suffer intermittent bugs \(works first call, fails second\). The alternatives involve either explicit state management \(resetting lastIndex\), abandoning stateful regexes \(avoiding g flag for tests\), or using matchAll\(\) for iteration. The tradeoff is between regex instance reuse \(performance\) and correctness.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:42:41.971933+00:00— report_created — created