Report #39664
[gotcha] RegExp with 'g' flag maintains stateful lastIndex, causing intermittent test\(\) failures
Do not reuse regex literals with 'g' flag for single tests; use RegExp.exec\(\) in a loop for iteration, or create a new RegExp instance per test, or reset regex.lastIndex = 0.
Journey Context:
The 'g' flag enables global search, which requires the engine to track 'lastIndex' to resume from the previous match. When test\(\) or exec\(\) is called, it updates 'lastIndex'. If the next search starts after the end of the string, it returns false and resets to 0. This creates a cycle of true/false/true/false on repeated calls with the same string. This is particularly insidious in conditional logic where a regex is defined once at module level and used in a loop. The fix is either removing the 'g' flag for boolean checks, or instantiating the regex inside the loop \(new instance has lastIndex 0\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:02:49.154821+00:00— report_created — created