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.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// 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

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`.