正则表达式中使用test方法时不要忽略lastIndex属性带来的影响

const handlePage = (page) => {
	const reg = new RegExp(`${page}_`, "g");
	return (action) => {
		if(!reg.test(action.type)){
			return "error";
		}
		return "success";
	}
}
const pageBack = handlePage("auth");

今天在写react的时候,写了类似于上面这样一段代码来封装action,结果发现当action.type是以${page}_开头时,也只是在奇数次的时候返回了success。

pageBack({ type: "auth_login" }) // success
pageBack({ type: "auth_loginout" }) // error
pageBack({ type: "auth_register" }) // success
pageBack({ type: "auth_reset" }) // error

找了很久才发现是由于RegExp创建的地方不对,最后改成如下形式:

const handlePage = (page) => {
	return (action) => {
		const reg = new RegExp(`${page}_`, "g");
		if(!reg.test(action.type)){
			return "error";
		}
		return "success";
	}
}
const pageBack = handlePage("auth");
pageBack({ type: "auth_login" }) // success
pageBack({ type: "auth_loginout" }) // success
pageBack({ type: "auth_register" }) // success
pageBack({ type: "auth_reset" }) // success

为什么两种写法结果不一样呢,这是因为每个RegExp都有一个lastIndex属性,当使用test方法且全局匹配时(g),如果能匹配到结果,则返回true,且lastIndex会改变,下一次再调用test方法时,会从lastIndex指定的位置处开始检索;如果不能匹配到结果,则返回false,且lastIndex属性置0

var reg1 = /^test/g;
reg1.test("test11");  // true
reg1.lastIndex  // 4
reg1.test("test22")  // false
reg1.lastIndex  // 0

var reg2 = /^test/;
reg2.test("test11");  // true
reg2.lastIndex  // 0
reg2.test("test22")  // true

如果不是全局匹配,则每次调用test方法时,lastIndex都是0,即每次都是从字符串最开始位置进行匹配查找。

更多关于RegExp对象的属性和方法>>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值