Report #22354
[gotcha] RegExp with global or sticky flag mutates lastIndex causing subsequent exec/test to fail on different strings
Reset lastIndex to 0 before each test/exec if the regex is global/sticky; or better, avoid using the same RegExp instance for multiple tests if it has global/sticky flags—create a new instance or clone it
Journey Context:
Developers often define a global regex constant at module level \(const RE = /foo/g\) and use it in utility functions. Because the g flag is needed for matchAll or replace, they keep it. However, methods like .test\(\) and .exec\(\) are stateful for global/sticky regexes—they advance the lastIndex property. If a match is found, lastIndex is updated to the end of the match; if not, it's reset to 0. This means calling test\(\) twice on the same string with the same global regex can return different results \(first true, second false\). This is a classic footgun that causes flaky tests and production bugs.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T15:56:00.111429+00:00— report_created — created