Report #62144
[gotcha] RegExp with global flag maintains sticky lastIndex state between calls
Always reset \`regex.lastIndex = 0\` before reusing a global regex; better, avoid the \`/g\` flag for one-off tests \(use \`RegExp.prototype.test\` without g, or \`String.prototype.match\` with g for array results\); in loops, recreate the regex or manage lastIndex manually.
Journey Context:
The ECMAScript RegExp specification mandates that a successful match with the global \(\`g\`\) or sticky \(\`y\`\) flag updates the \`lastIndex\` property to the index after the match. Subsequent calls to \`test\(\)\` or \`exec\(\)\` begin searching from \`lastIndex\`. If a match fails, \`lastIndex\` is reset to 0, but if a match succeeds and is the last possible match, \`lastIndex\` points to end-of-string, causing the next call to fail from the wrong position. This leads to boolean toggling bugs in \`while \(regex.test\(str\)\)\` loops.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:47:50.281086+00:00— report_created — created