为什么我的 javascript regex.test()会给出不同的结果

可能的复制品:
Javascript regex 返回 true. . then false. . then true. . etc

var r = /\d/g;
var a = r.test("1"); // will be true
var b = r.test("1"); // will be false
console.log(a == b); // will be false

请告诉我为什么 r.test("1")的结果与每个呼叫交替?

我可以通过移除 g 修饰符来解决这个问题。然而,我仍然想知道为什么会发生这种情况。

16457 次浏览

When you're using /g, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.

(This is a duplicate of Javascript regex returning true.. then false.. then true.. etc)