Report #86230
[gotcha] RegExp with global flag \(g\) persists lastIndex causing test\(\) or exec\(\) to skip matches on different strings
Always reset lastIndex to 0 before using a regex with the g or y flag on a new string, or avoid reusing regex instances with g/y flags across different strings. Prefer creating a new RegExp instance inside the function or use String.prototype.matchAll which handles state correctly.
Journey Context:
Developers often compile a regex at module level to avoid recompilation costs, then use it to test multiple strings in a loop or different functions. With the global flag, the regex engine tracks the position of the last match in the lastIndex property. On the next call with a \*different\* string, it starts searching from that stale index, often returning false immediately even if the new string contains a match. This is particularly insidious because the bug appears as 'it works the first time but fails randomly afterwards'. The y \(sticky\) flag makes this even more explicit but the g flag is the silent killer. The alternative of not using the flag loses the ability to find multiple matches in one string, but for simple existence checks \(test\), dropping the g flag is the correct fix.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T03:19:32.247009+00:00— report_created — created