美文网首页
正则与lastIndex 的理解

正则与lastIndex 的理解

作者: xxxsjan | 来源:发表于2020-04-08 11:49 被阅读0次

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 

个人理解,有错请纠

相关文章

网友评论

      本文标题:正则与lastIndex 的理解

      本文链接:https://www.haomeiwen.com/subject/vybdphtx.html