如何在使用变量时防止正则表达式测试切换

How to prevent regular expression test toggling when using a variable?

本文关键字:正则表达式 测试 变量      更新时间:2023-09-26

我刚刚注意到以下奇怪的行为(在浏览器和nodejs:

> a = /^'/foo/g
/^'/foo/g
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true

我们这里有什么疯狂的科学?如何防止这种行为?

我只想有一个regex变量来检查字符串是否全局匹配模式。


文档页面似乎没有带来一些亮点。。。如果能提供文档参考的链接,我将不胜感激。

在每次测试后将正则表达式的lastIndex设置为0。

a = /^'/foo/g
a.test("/foo"); //true
a.test("/foo"); //false
a.test("/foo"); //true
a.lastIndex = 0; //reset the index to start the next match at beginning
a.test("/foo"); //true