bug描述: 正则表达式使用全局模式时,会从前之后匹配每一个字符,完成之后其lastIndex属性值不会重置,所以重复使用同一正则会出现结果不一致现象
var reg = /^[0-9]*$/g;
console.log(reg.test("12345")); // true
console.log(reg.lastIndex); // 5
console.log(reg.test("12345")); // false
console.log(reg.lastIndex); // 0
解决方法:
- 不使用全局匹配
- 在一次检查后手动重置lastIndex为0
var reg = /^[0-9]*$/g;
console.log(reg.test("12345")); // true
reg.lastIndex = 0;
console.log(reg.test("12345")); // true