在JavaScript中,正则表达式的全局标志g会显著改变test()方法的行为。理解这一特性对于正确处理字符串匹配至关重要。
当正则表达式未使用全局标志时,test()方法每次都会从字符串起始位置开始匹配:
const regex = /\d/;
const str = '123';
console.log(regex.test(str)); // true
console.log(regex.test(str)); // true(始终返回相同结果)
当添加全局标志后,正则表达式会维护一个lastIndex属性,记录上次匹配的结束位置:
const regex = /\d/g;
const str = '123';
console.log(regex.test(str)); // true(匹配'1', lastIndex=1)
console.log(regex.test(str)); // true(匹配'2', lastIndex=2)
console.log(regex.test(str)); // true(匹配'3', lastIndex=3)
console.log(regex.test(str)); // false(无更多匹配,重置lastIndex=0)
lastIndex = 0可重置匹配位置regex.lastIndex = 0显式重置匹配状态match()或matchAll()进行全局匹配