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

标签 javascript regex node.js

<分区>

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

> 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

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

我只想有一个正则表达式变量来检查字符串是否与全局模式匹配。


Documentation pages似乎没有给那里带来一些光明……我真的很感激指向文档引用的链接。

最佳答案

设置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

关于javascript - 使用变量时如何防止正则表达式测试切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659840/

相关文章:

java - 删除标点符号,保留字母和空格 - Java Regex

javascript - 在不解决 promise 的情况下使用 $http.post 和 res.redirect

Javascript match() 和无效量词

mysql - 我可以在一个格式优美的 SQL 查询中查询 285 个 ID 和 URL

javascript - 填充底部在生成的文档中不起作用

javascript - 在 Node、Express With Multer 中上传之前验证图像宽度和高度

mysql - 在数据库(mysql)的情况下,kubernetes 服务如何工作?

javascript - 添加 key :value to a . json 文件

javascript - 当所有项目都已在 Ruby on Rails 中呈现时,隐藏“加载更多”按钮

javascript - 对象内函数中的 this 关键字