js正则多次test下结果不一致问题
文章目录
在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
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论