我是瘦子

JavaScript 相同的正则多次调用 test() 返回的值却不同的问题

代码如下:

1
2
3
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.test(15328044636)); // => true
console.log(reg.test(15328044636)); // => false

问题原因

这是因为正则 reg 的 g 属性,设置的全局匹配。RegExp 有一个 lastIndex 属性,来保存索引开始位置。上面的问题,第一次调用的 lastIndex 值为0,到了第二次调用,值变成了11。如果正则匹配失败,lastIndex 会被重置为 0。

1
2
3
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.lastIndex, reg.test(15328044636)); // => 0 true
console.log(reg.lastIndex, reg.test(15328044636)); // => 11 false

解决方案

第一种方案是将 g 去掉,关闭全局匹配。
第二种就是在每次匹配之前将 lastIndex 的值设置为0。

1
2
3
4
var reg = /^1[345678][0-9]{9}$/g;
console.log(reg.lastIndex, reg.test(15328044636)); // => 0 true
reg.lastIndex = 0;
console.log(reg.lastIndex, reg.test(15328044636)); // => 0 true

本文转载自:https://www.jianshu.com/p/a9840a5bc6cc