全局
g
模式下,无论是test
还是exec
,改变的都是同一个lastIndex
,哪怕再次匹配的是一个新字符串,lastIndex
还是会继承之前的改变。假如中间使用字符串方法例如:str.match(reg)
,则会使lastIndex
变为0
重新开始。
示例一:
let str='abc123';
let reg=/\d+/g; // 注意这里的 g,没有 g 的话下一次是重新开始
if(reg.test(str)){
console.log(reg.lastIndex); // 6
console.log(reg.exec(str)); // null 注意 exec 匹配到一个结果就返回,不会继续,即使全局匹配,再执行一次才会匹配下一个
}
示例二:
let str = 'abc123bba245';
let reg = /\d+/g;
console.log(reg.exec(str)); // Array [ "123" ]
console.log(reg.lastIndex); // 6
console.log(reg.exec('af4f59l66')); // Array [ "66" ]
console.log(reg.lastIndex); // 9
console.log(reg.exec(str)); // Array [ "245" ]
示例三:
let str = 'abc123bba245';
let reg = /\d+/g;
console.log(reg.exec(str)); // Array [ "123" ]
console.log(reg.lastIndex); // 6
console.log(str.match(reg)); // Array [ "123", "245" ]
console.log(reg.lastIndex); // 0
console.log(reg.exec('af4f59l66')); // Array [ "4" ]
console.log(reg.lastIndex); // 3
console.log(str.replace(reg, '-')); // abc-bba-
console.log(reg.exec(str)); // Array [ "123" ]
网友评论