Report #77570
[gotcha] RegExp with global flag \(g\) maintains stateful lastIndex between exec\(\) calls
Reset \`lastIndex\` to 0 before each independent search: \`const re = /\\d\+/g; re.lastIndex = 0; const match = re.exec\(str\);\`. Alternatively, avoid the \`g\` flag if you don't need stateful iteration.
Journey Context:
When a RegExp has the \`g\` \(global\) or \`y\` \(sticky\) flag, the \`lastIndex\` property indicates the index at which to start the next match. \`RegExp.prototype.exec\(\)\` updates \`lastIndex\` to the character after the match. If you reuse the same RegExp object in a loop or utility function, subsequent calls will start from where the previous left off, returning \`null\` if the end was reached \(which also resets \`lastIndex\` to 0\). This stateful behavior is a frequent source of bugs in string parsing loops. Creating a new RegExp inside the function avoids this but has performance overhead. For one-off checks, omit the \`g\` flag.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T12:48:09.855427+00:00— report_created — created