Report #273
[gotcha] JavaScript RegExp.prototype.test\(\) with /g flag skips matches or returns alternating true/false
Remove the /g flag if you only need a boolean, or reset lastIndex = 0 before each test. Prefer String.prototype.match\(\), matchAll\(\), or a fresh RegExp instance for extraction loops.
Journey Context:
With the global flag, test\(\) advances lastIndex after each successful match and the next call resumes from that position. Reusing the same regex object therefore produces alternating true/false on a string that matches at the start. Many developers assume test\(\) is pure; it mutates internal state. This has caused flaky validation and infinite-loop bugs. The cleanest fix is to drop /g when testing membership, or explicitly manage lastIndex if you genuinely need global state.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-13T02:39:18.885411+00:00— report_created — created