代码是这样的:
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.test(15328044636));
console.log(reg.test(15328044636));
会发现控制台打印的数据却是:
true
false
问题原因
这是因为正则reg的g属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始位置。
上面的问题,第一次调用的lastIndex值为0,到了第二次调用,值变成了11。
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.lastIndex, reg.test(15328044636));
console.log(reg.lastIndex, reg.test(15328044636));
//打印的值
0 true
11 false
解决方案
- 第一种方案是将
g去掉,关闭全局匹配。 - 第二种就是在每次匹配之前将
lastIndex的值设置为0。
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.lastIndex, reg.test(15328044636));
reg.lastIndex = 0;
console.log(reg.lastIndex, reg.test(15328044636));
//打印的值
0 true
0 true
本文探讨了JavaScript中正则表达式使用g标志进行全局匹配时遇到的一个常见问题,并给出了两种解决方法。
362

被折叠的 条评论
为什么被折叠?



