Report #15572
[gotcha] Reusing a RegExp with global flag \(g\) causes it to fail on subsequent calls due to lastIndex state
Instantiate the regex inside the loop/function, or manually reset \`regex.lastIndex = 0\` before reuse. Avoid the \`g\` flag entirely if you are only testing for existence \(use \`RegExp.prototype.test\` without \`g\` or use \`String.prototype.includes\`\).
Journey Context:
The \`g\` \(global\) and \`y\` \(sticky\) flags make RegExp instances stateful. Per the ECMA-262 spec, \`RegExp.prototype.exec\` reads and writes the \`lastIndex\` property. After a match, \`lastIndex\` is set to the index after the match. If you reuse the same regex instance on a new string, it starts searching from that stale \`lastIndex\`. If the new string is shorter, it immediately returns \`null\` and only then resets \`lastIndex\` to 0. This creates heisenbugs where the second call to a utility function fails with the same regex. Creating a new regex per invocation avoids the state machine entanglement entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T00:25:21.683772+00:00— report_created — created