您好,欢迎访问一九零五行业门户网

lastIndex与正则表达式的关系

这次给大家带来lastindex与正则表达式的关系,使用lastindex与正则表达式的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
今天遇到一个问题,用正则表达式去检查同一个字符串时,交替返回true和false。无奈之下,重新翻了翻权威指南,发现罪魁祸首原来是lastindex。可在控制台尝试下
let reg = /[\d]/g //undefined reg.test(1) //true reg.test(1) //false
lastindex
lastindex在权威指南中是如下解释:它是一个可读/写的整数。如果匹配模式带有g修饰符,这个属性存储在整个字符串中下次索引的开始位置,这个属性会被exec()和test()用到。还是上面的例子,观察下lastindex属性
let reg = /[\d]/g  //有修饰符g //undefined reg.lastindex //0 reg.test(1)    //true reg.lastindex  //匹配一次后,lastindex改变 //1 reg.test(1)  //从index 1 开始匹配 //false reg.lastindex //0 reg.test(1) //true reg.lastindex //1
第一次使用test()匹配成功后,lastindex被设为匹配到的结束位置,就是1;第二次再test()时,从index 1 开始匹配,匹配失败,lastindex重置为0 。这样就造成了匹配结果与预期不符
解决
1、不使用 g 修饰符
reg = /[\d]/ ///[\d]/ reg.test(1) //true reg.test(1) //true reg.lastindex //0 reg.test(1) //true reg.lastindex
2、test()之后手动设置lastindex = 0
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
正则表达式的\d元字符(等价于[^0-9])使用详解
常用正则表达式的整理
以上就是lastindex与正则表达式的关系的详细内容。
其它类似信息

推荐信息