Global Regex lastIndex Reuse Pitfall
A g-flag regex object carries lastIndex across exec and test calls, so reusing one literal skips matches until you reset it or use matchAll.
Code
// Pitfall: a g-flag regex object is stateful — exec and test advance lastIndex
const digits = /\d+/g;
console.log('exec 1:', digits.exec('a1 b22 c333')[0], 'lastIndex:', digits.lastIndex);
console.log('exec 2:', digits.exec('a1 b22 c333')[0], 'lastIndex:', digits.lastIndex);
console.log('exec 3:', digits.exec('a1 b22 c333')[0], 'lastIndex:', digits.lastIndex);
console.log('exec 4 (exhausted):', digits.exec('a1 b22 c333'));
// reusing one literal across .test() calls keeps the stale cursor
const voucher = /\d+/g;
console.log('initial test:', voucher.test('code 42')); // advances lastIndex to 7
console.log('stale test skips 99:', voucher.test('99 bottles'));
voucher.lastIndex = 0;
console.log('test after reset:', voucher.test('99 bottles'));
// stateless alternative: matchAll, or a fresh literal per call
console.log('matchAll:', [...'a1 b22 c333'.matchAll(/\d+/g)].map((m) => m[0]));
// without the g flag there is no lastIndex side effect at all
const plain = /\d+/;
console.log('no g flag, repeated test:', plain.test('x9'), plain.test('x9'), plain.lastIndex);What the code does
The file’s state is a handful of top-level bindings: digits, voucher, plain.
Applying it
The run emits 9 labeled sections — exec 1:, exec 2:, exec 3:, exec 4 (exhausted):, initial test:, stale test skips 99:, test after reset:, matchAll:, no g flag, repeated test: — one per step.
Statements that matter
const voucher = /\d+/g;
const digits = /\d+/g;
voucher.lastIndex = 0;
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `digits`, `voucher`, `plain`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.