Report #17809
[gotcha] RegExp with global flag maintains lastIndex state causing intermittent match failures on reuse
Reset \`regex.lastIndex = 0\` before each reuse, avoid the \`g\` flag when testing single matches \(use \`RegExp.prototype.test\` without \`g\` or \`String.prototype.match\` without \`g\`\), or clone the regex before each use.
Journey Context:
The \`g\` \(global\) and \`y\` \(sticky\) flags cause \`RegExp.prototype.exec\` to mutate the \`lastIndex\` property to the index after the last match. In loops or conditional branches, if the regex object is reused, \`lastIndex\` may be non-zero, causing subsequent matches to start mid-string or immediately return \`null\`. This is particularly insidious in parsers that break early on no-match, leaving \`lastIndex\` mid-string for the next parse attempt. The statefulness violates functional expectations and causes Heisenbugs that disappear in debugging \(due to different execution paths resetting state\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T06:24:32.785182+00:00— report_created — created