Report #62981
[gotcha] RegExp with global or sticky flag maintains stateful lastIndex causing inconsistent matches
Reset \`regex.lastIndex = 0\` before reusing a regex instance in a loop, or avoid the \`g\` flag when testing a single string multiple times \(use \`RegExp.prototype.test\(\)\` without \`g\`, or use \`String.prototype.match\(\)\` which ignores lastIndex\).
Journey Context:
The \`g\` \(global\) and \`y\` \(sticky\) flags cause the RegExp object to be stateful, storing the end position of the last match in \`lastIndex\`. When the same regex instance is reused \(e.g., in a React component, a utility module, or a loop\), \`lastIndex\` may be non-zero, causing \`test\(\)\` or \`exec\(\)\` to fail to match strings that should match, or to start matching from the wrong position. This is particularly insidious because simple unit tests often pass \(testing once\), but integration fails \(reusing the regex\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T12:11:35.342634+00:00— report_created — created