当前位置: 首页 > Web前端 > JavaScript

多次测试下js正则化结果不一致

时间:2023-03-27 15:36:02 JavaScript

在javascript中定义正则变量reg,使用reg.test,多次测试结果会不同。如下图:letcondi=/test/giconsole.log(condi.test("Test1"))//trueconsole.log(condi.test("Test2"))//falseconsole.log(condi.test("Test3"))//trueconsole.log(condi.test("Test4"))//falseconsole.log(condi.test("Test5"))//true为什么会出现这个结果?原因是RegExp对象的lastIndex属性,看W3s上的定义,问题就明白了。第一次匹配“Test1”时,lastIndex为0,匹配结果为true。第二次匹配“Test2”时,lastIndex为2,匹配结果为false,匹配到字符串末尾,lastIndex重置为0,第三次匹配时为true。.等等,我们打印出这个lastIndex:condi=/test/giconsole.log(condi.lastIndex,condi.test("Test1"))//0trueconsole.log(condi.lastIndex,condi.test("测试2"))//2falseconsole.log(condi.lastIndex,condi.test("测试3"))//0trueconsole.log(condi.lastIndex,condi.test("测试4"))//2falseconsole.log(condi.lastIndex,condi.test("Test5"))//0truefor为了更好的理解这个lastIndex,让我们再看看这个例子:condi=/test/gistr="Test1Test2Test3测试4测试5"console.log(condi.lastIndex,condi.test(str));//0trueconsole.log(condi.lastIndex,condi.test(str));//2trueconsole.log(condi.lastIndex,condi.test(str));//5trueconsole.log(condi.lastIndex,condi.test(str));//8trueconsole.log(condi.lastIndex,condi.test(str));//11true使用全局搜索(/g)时,需要注意lastIndex,否则可能会导致不需要的结果condi=/test/giconsole.log(condi.lastIndex,condi.test("Test1"))//0truecondi.lastIndex=0;console.log(condi.lastIndex,condi.test("测试2"))//0truecondi.lastIndex=0;console.log(condi.lastIndex,condi.test("测试3"))//0truecondi.lastIndex=0;console.log(condi.lastIndex,condi.test("Test4"))//0truecondi.lastIndex=0;console.log(condi.lastIndex,condi.test("测试5"))//0为真