Report #8203
[gotcha] RegExp global \(g\) and sticky \(y\) flags maintain mutable lastIndex causing intermittent test\(\) failures
Never use regex.test\(\) or regex.exec\(\) in loops or conditional checks with global/sticky flags unless you manually reset lastIndex to 0 before each use; prefer String.prototype.match\(\) or matchAll\(\) which do not mutate the regex state.
Journey Context:
A RegExp with /g or /y flags is stateful. When test\(\) or exec\(\) is called, it updates the lastIndex property to the position after the match. Subsequent calls start searching from lastIndex, not index 0. If the string changed or the previous match was at the end, test\(\) returns false unexpectedly. This causes 'flaky' tests that pass in isolation but fail in loops. The common fix is resetting regex.lastIndex = 0 before use, but this is error-prone. The better architectural decision is to avoid stateful regex methods entirely and use String.match\(\) for one-offs or String.matchAll\(\) \(ES2020\) for iteration, which return fresh iterator state without mutating the source regex.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T04:50:23.544559+00:00— report_created — created