当test()被调用两次时,为什么"g"修饰符会给出不同的结果?

NSt*_*tal 16 javascript regex

鉴于此代码:

var reg = /a/g;
console.log(reg.test("a"));
console.log(reg.test("a"));
Run Code Online (Sandbox Code Playgroud)

我得到这个结果:

true
false
Run Code Online (Sandbox Code Playgroud)

我不知道这是怎么发生的.我已经在Node.js(v8)和Firefox浏览器中进行了测试.

Mik*_*uel 24

要解决此问题,您可以删除g标记或重置lastIndex

var reg = /a/g;
console.log(reg.test("a"));
reg.lastIndex = 0;
console.log(reg.test("a"));
Run Code Online (Sandbox Code Playgroud)

问题出现的原因testexec,在第一个传递相同字符串并且g存在标志之后,在第一个之后查找更多匹配.

15.10.6.3 RegExp.prototype.test(string)#ⓉⓇ

采取以下步骤:

  1. 匹配是使用字符串作为参数RegExp.prototype.exec在此RegExp对象上评估(15.10.6.2)算法的结果.
  2. 如果比赛是不是null,则返回true; 别的回来false.

关键部分exec15.10.6.2的第6 :

6.让global成为使用参数"global"调用R的[[Get]]内部方法的结果.
7.如果global为false,则让i = 0.

i未重置为0时,exec(因此test)不会开始查看字符串的开头.

这很有用,exec因为你可以循环来处理每个匹配:

 var myRegex = /o/g;
 var myString = "fooo";
 for (var match; match = myRegex.exec(myString);) {
   alert(match + " at " + myRegex.lastIndex);
 }
Run Code Online (Sandbox Code Playgroud)

但显然它不是那么有用test.