在javascript中定义正则变量reg,应用reg.test,屡次test下后果不同。如下图所示:
let condi = /测试/giconsole.log(condi.test("测试1")) //trueconsole.log(condi.test("测试2")) //falseconsole.log(condi.test("测试3")) //trueconsole.log(condi.test("测试4")) //falseconsole.log(condi.test("测试5")) //true
为何会产生这个后果?起因在于RegExp对象的lastIndex属性,看看W3s上的定义
问题清晰了,在第一次匹配"测试1"的时候,lastIndex为0,匹配后果true,第二次匹配"测试2"的时候,lastIndex为2,匹配后果false,字符串匹配到尾了,lastIndex重置为0,第三次匹配的时候就是true...以此类推
咱们打印出这个lastIndex:
condi = /测试/giconsole.log(condi.lastIndex,condi.test("测试1")) // 0 trueconsole.log(condi.lastIndex,condi.test("测试2")) // 2 falseconsole.log(condi.lastIndex,condi.test("测试3")) // 0 trueconsole.log(condi.lastIndex,condi.test("测试4")) // 2 falseconsole.log(condi.lastIndex,condi.test("测试5")) // 0 true
为了更好了解这个lastIndex,咱们再看看这个例子:
condi = /测试/gistr = "测试1测试2测试3测试4测试5"console.log(condi.lastIndex,condi.test(str)); // 0 trueconsole.log(condi.lastIndex,condi.test(str)); // 2 trueconsole.log(condi.lastIndex,condi.test(str)); // 5 trueconsole.log(condi.lastIndex,condi.test(str)); // 8 trueconsole.log(condi.lastIndex,condi.test(str)); // 11 true
在应用全局搜寻(/g)的时候,须要留神lastIndex,否则可能导致本人不想要的后果
condi = /测试/giconsole.log(condi.lastIndex,condi.test("测试1")) // 0 truecondi.lastIndex = 0;console.log(condi.lastIndex,condi.test("测试2")) // 0 truecondi.lastIndex = 0;console.log(condi.lastIndex,condi.test("测试3")) // 0 truecondi.lastIndex = 0;console.log(condi.lastIndex,condi.test("测试4")) // 0 truecondi.lastIndex = 0;console.log(condi.lastIndex,condi.test("测试5")) // 0 true