关于javascript:js正则多次test下结果不一致问题

3次阅读

共计 1424 个字符,预计需要花费 4 分钟才能阅读完成。

在 javascript 中定义正则变量 reg, 应用 reg.test, 屡次 test 下后果不同。如下图所示:

let condi = / 测试 /gi
console.log(condi.test("测试 1")) //true
console.log(condi.test("测试 2")) //false
console.log(condi.test("测试 3")) //true
console.log(condi.test("测试 4")) //false
console.log(condi.test("测试 5")) //true

为何会产生这个后果? 起因在于 RegExp 对象的 lastIndex 属性,看看 W3s 上的定义

问题清晰了,在第一次匹配 ” 测试 1 ″ 的时候,lastIndex 为 0,匹配后果 true,第二次匹配 ” 测试 2 ″ 的时候,lastIndex 为 2,匹配后果 false, 字符串匹配到尾了,lastIndex 重置为 0,第三次匹配的时候就是 true… 以此类推

咱们打印出这个 lastIndex:

condi = / 测试 /gi
console.log(condi.lastIndex,condi.test("测试 1")) // 0 true
console.log(condi.lastIndex,condi.test("测试 2")) // 2 false
console.log(condi.lastIndex,condi.test("测试 3")) // 0 true
console.log(condi.lastIndex,condi.test("测试 4")) // 2 false
console.log(condi.lastIndex,condi.test("测试 5")) // 0 true

为了更好了解这个 lastIndex,咱们再看看这个例子:

condi = / 测试 /gi
str = "测试 1 测试 2 测试 3 测试 4 测试 5"
console.log(condi.lastIndex,condi.test(str)); // 0 true
console.log(condi.lastIndex,condi.test(str)); // 2 true
console.log(condi.lastIndex,condi.test(str)); // 5 true
console.log(condi.lastIndex,condi.test(str)); // 8 true
console.log(condi.lastIndex,condi.test(str)); // 11 true

在应用全局搜寻 (/g) 的时候, 须要留神 lastIndex,否则可能导致本人不想要的后果

condi = / 测试 /gi
console.log(condi.lastIndex,condi.test("测试 1")) // 0 true
condi.lastIndex = 0;
console.log(condi.lastIndex,condi.test("测试 2")) // 0 true
condi.lastIndex = 0;
console.log(condi.lastIndex,condi.test("测试 3")) // 0 true
condi.lastIndex = 0;
console.log(condi.lastIndex,condi.test("测试 4")) // 0 true
condi.lastIndex = 0;
console.log(condi.lastIndex,condi.test("测试 5")) // 0 true
正文完
 0