如何防止使用variables时切换正则expression式testing?

我只注意到以下奇怪的行为(无论是在浏览器和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 

我们这里有什么疯狂的科学? 我怎样才能防止这种行为?

我只想要一个正则expression式variables,检查一个string是否与全局匹配。


文档页面似乎没有带来一些光线…我真的很感激链接到文档参考。

在每次testing之后,将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