← 中文资源

简体中文版本

g 标志正则的 lastIndex 残留

带 g 标志的正则对象会在 exec 与 test 之间推进 lastIndex:复用同一个字面量会跳过新字符串开头的匹配,置零重置或改用 matchAll 才可靠。

阅读英文原文

实现说明

顶层就这几处状态:digits、voucher、plain。

使用要点

  • 直接运行文件,输出会带上标签,比如 exec 1:、exec 2:、exec 3:——输出的每一行都能指回产生它的那次调用。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 状态都挂在模块顶层:digits、voucher、plain。

核心语句

const voucher = /\d+/g;
const digits = /\d+/g;
voucher.lastIndex = 0;

代码示例

// 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);