【正则表达式】为什么reg.test()一次为true,一次为false

374 阅读1分钟

实例

const reg = /^a$/g;
cosnt str = 'a';
console.log(reg.test(str)); // true
console.log(reg.test(str)); // false
console.log(reg.test(str)); // true

产生原因

因为设置了g(全局属性),因此lastIndex(用于规定下次匹配的起始位置)起作用。
第一次从str[0]开始匹配到'a',结果为true。 lastIndex = 1
第二次从str[1]开始匹配,没有匹配到值,结果为false。 lastIndex = 0
第三次又会从str[0]开始匹配,所以为true。 lastIndex = 1

解决办法

  1. 取消全局属性g

  2. 每次匹配成功后修改lastIndex值(可读可写的属性)

reg.test(str); // true
reg.lastIndex = 0; 
reg.test(str); // true