正则与lastIndex 的理解

2020-04-08  本文已影响0人  xxxsjan

lastIndex --不是匹配最后字符串的lastIndexOf

例子说明

var str = 'google'
var reg = /o/g
console.log(reg.test(str), reg.lastIndex) // true 2 --找到go lastIndex设为下一位索引,2
console.log(reg.test(str), reg.lastIndex) // true 3 --根据之前lastIndex开始找,即从go的下一位开始找,找到o,lastIndex设为3
console.log(reg.test(str), reg.lastIndex); // false 0 --根据之前lastIndex开始找,即从goo的下一位开始找,没找到,lastIndex设为0

不具有标志 g 和不表示全局模式的 RegExp 对象不能使用 lastIndex 属性, lastIndex一直是0

var reg2 = /o/
console.log(reg2.test(str), reg2.lastIndex) // true 0 
console.log(reg2.test(str), reg2.lastIndex) // true 0 
console.log(reg2.test(str), reg2.lastIndex); // true 0 

个人理解,有错请纠

上一篇 下一篇

猜你喜欢

热点阅读