Report #8931
[gotcha] RegExp with global or sticky flag maintains lastIndex state between calls
Reset lastIndex to 0 before each use if reusing a regex instance, or instantiate the RegExp inside the loop/function. Alternatively, use String.prototype.matchAll\(\) which returns an iterator and does not mutate the regex's lastIndex.
Journey Context:
The RegExp prototype maintains a lastIndex property when the global \('g'\) or sticky \('y'\) flag is set. Methods like exec\(\), test\(\), match\(\), replace\(\), split\(\), and search\(\) update this property to the index after the last match. If you reuse the same RegExp instance in a loop or across function calls without resetting lastIndex, subsequent calls may fail to match valid strings because the search starts from the old offset. This creates non-deterministic 'works in console, fails in production' bugs. The fix is to either reset lastIndex to 0 before use, avoid shared state by creating fresh instances, or use matchAll\(\) which handles iteration without mutating state.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T06:48:16.360212+00:00— report_created — created