js正则属性详解 外加踩过的一个的坑(lastIndex)

每个RegExp对象都包含5个属性,source、global、ignoreCase、multiline、 l a s t I n d e x

先简单的介绍下五个属性

1.source:是一个只读的字符串,包含正则表达式的文本。

const reg = /haha/;
console.log(reg.source);  //haha

2. global:是一个只读的布尔值,判断正则表达式是否带有修饰符g。

修饰符g,是全局匹配的意思,检索字符串中所有的匹配。

var reg = /haha/;
console.log(reg.global); //返回 false

var reg = /haha/g;
console.log(reg.global); //返回 true

3. ignoreCase:是一个只读的布尔值,判断正则表达式是否带有修饰符i。

修饰符i,说明模式匹配是不区分大小写的。

var reg = /haha/;
console.log(reg.ignoreCase); //返回 false

var reg = /haha/i;
console.log(reg.ignoreCase); //返回 true

4. multiline:是一个只读的布尔值,判断正则表达式是否带有修饰符m。

修饰符m,用以在多行模式中执行匹配,需要配合^ 和 使 使 除了匹配整个字符串的开始和结尾之外,还能匹配每行的开始和结尾。

var reg=/haha/;
reg.multiline; //返回false

var reg=/haha/m;
reg.multiline; //返回true

5. l a s t I n d e x :是一个可读/写的整数,如果匹配模式中带有g修饰符,这个属性存储在整个字符串中下一次检索的开始位置,这个属性会被exec( ) 和 test( ) 方法用到。

l a s t I n d e x 这个属性可能会踩坑的0.0。会导致有时候返回值出错有时候正确。 这个坑的错误是建立在g也就是全局的基础之上的。

  • exec( )方法是在一个字符串中执行匹配检索,如果它没有找到任何匹配,它就返回null,但如果它找到了一个匹配,它就返回一个数组(数组参数第一个就是reg.source ,第二个是index,开始查询位置,第三个是 str)。
  • test() test( )方法,它的参数是一个字符串,用test( )对某个字符串进行检测,如果包含正则表达式的一个匹配结果,则返回true,否则返回false。
const reg = /haha/g;
const str = "haha haha"
console.log(reg.exec(str)); //["haha", index: 0, input: "haha haha", groups: undefined]
console.log(reg.lastIndex); //4

console.log(reg.exec(str)); // ["haha", index: 5, input: "haha haha", groups: undefined]
console.log(reg.lastIndex); //9

console.log(reg.exec(str)); //null
console.log(reg.lastIndex); // 0

/*它将把当前正则表达式对象的lastIndex属性设置为紧挨着匹配子串的字符位置,当同一个正则表达式第二次调用exec( ),它会将从lastIndex属性所指示的字符串处开始检索,如果exec( )没有发现任何匹配结果,它会将lastIndex重置为0。*/

console.log(reg.exec(str)); // ["haha", index: 0, input: "haha haha", groups: undefined]
console.log(reg.lastIndex); //4
const str="haha haha";
const reg=/haha/g;

console.log(reg.test(str)); //打印 true

console.log(reg.lastIndex);
//打印4,因为匹配到了JavaScript,所以设置lastIndex为匹配结果紧挨着的字符位置

console.log(reg.test(str)); //打印 true

console.log(reg.lastIndex);
//打印9,因为匹配到了JavaScript,所以设置lastIndex为匹配结果紧挨着的字符位置

console.log(reg.test(str));
//打印 false,因为从lastIndex位置检索字符串,已经没有匹配结果了

console.log(reg.lastIndex);
//打印0,因为没有匹配到结果,所以将lastIndex重置为0

不想踩坑的话 。如果在一个字符串中完成了一次模式匹配之后要开始检索新的字符串,就必须手动地把 lastIndex 属性重置为 0。

例如:

const str="haha haha";
const reg=/haha/g;
console.log(reg.test(str)); //打印 true
reg.lastIndex=0;
console.log(reg.lastIndex);
//打印0,
console.log(reg.test(str)); //打印 true
reg.lastIndex=0;
console.log(reg.lastIndex);
//打印0,

console.log(reg.test(str));
//打印 true
reg.lastIndex=0;
console.log(reg.lastIndex);
//打印0,

在例如每次都new RegExp();构造一个新的 RegExp对象

const str="haha haha";
let reg = new RegExp("haha","g");

console.log(reg.test(str)); //打印 true
console.log(reg.lastIndex);
//打印4,
reg = new RegExp("haha","g");
console.log(reg.test(str)); //打印 true
console.log(reg.lastIndex);
//打印4,

reg = new RegExp("haha","g");
console.log(reg.test(str));
//打印 true
console.log(reg.lastIndex);
//打印4,

猜你喜欢

转载自blog.csdn.net/wen_binobject/article/details/80339277