JS RegExp中全局匹配(global)中踩过的坑
1、踩坑的代码,及结果
var str1 = 'I from Hunan';
var str2 = 'I from Jiangsu';
var pattern = /I from (Hunan|Jiangsu)/g;
console.log(pattern.test(str1));//结果为true
console.log(pattern.test(str2));//预计结果为true,实际false
我写这段代码出现这样结果不一致的原因是对lastIndex属性的了解不到位。
2、JavaScript lastIndex
属性
该属性存放一个整数,它声明的是上一次匹配文本之后的第一个字符的位置。上次匹配的结果是由方法 RegExp.exec() 和 RegExp.test() 找到的,它们都以 lastIndex 属性所指的位置作为下次检索的起始点。这样,就可以通过反复调用这两个方法来遍历一个字符串中的所有匹配文本。
该属性是可读可写的。只要目标字符串的下一次搜索开始,就可以对它进行设置
。当方法 exec() 或 test() 再也找不到可以匹配的文本时,它们会自动把 lastIndex 属性重置为 0。
3、再次了解了lastIndex属性后,测试lastIndex属性:
var str1 = 'I from Hunan';
var str2 = 'I from Jiangsu';
var pattern = /I from (Hunan|Jiangsu)/g;
console.log(pattern.lastIndex);//0,起始检索下标为0
console.log(pattern.test(str1));//结果为:true
console.log(pattern.lastIndex);//12
/*结果为false时,lastIndex 下次检索的起点重置为0*/
console.log(pattern.test(str2));//结果为:false
console.log(pattern.lastIndex);//0
/*再次test(str2),结果是true,*/
console.log(pattern.test(str2));//结果为:true
console.log(pattern.lastIndex);//14
4、解决方案
还是使用全局匹配:
var str1 = 'I from Hunan';
var str2 = 'I from Jiangsu';
var pattern = /I from (Hunan|Jiangsu)/g;
console.log(pattern.test(str1));//true
pattern.lastIndex = 0;
console.log(pattern.test(str2));//true
不使用全局匹配:
var str1 = 'I from Hunan';
var str2 = 'I from Jiangsu';
var pattern = /I from (Hunan|Jiangsu)/;
console.log(pattern.test(str1));//true
console.log(pattern.test(str2));//true