js正则全局匹配引发的血案

现象

  • 下面这个代码的输出毫无疑问,是true;

    const reg = /\d+/g;		//匹配数字
    reg.test(11111);		// true	
    
  • 如果我接着再test一遍呢

    const reg = /\d+/g;		//匹配数字
    reg.test(11111);		// true	
    reg.test(11111);		// false	
    

    这就是血案本案了

  • lastIndex观察

    const reg = /\d+/g;		//匹配数字
    console.log(reg.test(11111), reg.lastIndex);	// true, 0
    console.log(reg.test(11111), reg.lastIndex);	// false, 5
    console.log(reg.test(11111), reg.lastIndex);	// true, 0
    console.log(reg.test(11111), reg.lastIndex);	// false, 5
    console.log(reg.test(11111), reg.lastIndex);	// true, 0
    console.log(reg.test(11111), reg.lastIndex);	// false, 5
    
    
  • MDN中对于exec和test有如下介绍

    在设置了 global 或 sticky 标志位的情况下(如 /foo/g or /foo/y),JavaScript RegExp 对象是有状态的。他们会将上次成功匹配后的位置记录在 lastIndex 属性中

  • 处理方案1
    避免在test时使用g(废话);

  • 处理方案2
    每次test创建新的正则对象 :

    /\d/g.test(11111)		// true
    /\d/g.test(11111)		// true
    /\d/g.test(11111)		// true
    /\d/g.test(11111)		// true
    

    这其实也不太好,每次都实例化出一个新的正则对象;

  • 处理方案3
    lastIndex是可写的!!
    那就可以这样了:

    const reg = /\d+/g;		//匹配数字
    reg.test(11111);		// true	
    reg.lastIndex = 0;
    reg.test(11111);		// true	
    

    目前想到的就这三种,后面有想到其它的再来补吧;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值