JavaScript 值在变量中未正确评估,但作为字符串正常工作

标签 javascript regex

这个问题在这里已经有了答案:





Why does a RegExp with global flag give wrong results?

(7 个回答)


2年前关闭。




我不确定为什么这个评估只在一个变量中而不是在一个字符串中时会有所不同。我看不出任何逻辑。

const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)


var word = 'hundred';
console.log('isNum with string:', isNum('hundred')); // true
console.log('isNum with variable:', isNum(word));    // false
console.log('words are equal:', word === 'hundred'); // true

最佳答案

isNum正在返回 false当它在同一字符串上被第二次调用时。改变顺序,看到同样的东西:

const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)


var word = 'hundred';
console.log('isNum with variable:', isNum(word));    // true
console.log('isNum with string:', isNum('hundred')); // false
console.log('words are equal:', word === 'hundred'); // true
g flag 记住最后一场比赛的位置。删除它以解决问题:
const numRegex = /hundred|thousand|million|billion|trillion/i;

Mozilla talks more about this :

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

关于JavaScript 值在变量中未正确评估,但作为字符串正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461810/

相关文章:

javascript - 离屏幕最近的线系列解决方案不返回适当的值

javascript - OL3 v3.14.0 中的隐秘错误消息

regex - 具有奇数个 1 和至少一个 0 的正则表达式

regex - Linux命令sed中的正则表达式

C# RegEx 删除 span 标记并保留引号 char

javascript - $location.path 使用 Angularjs 单击按钮时未加载 html 文件

javascript - 在 Node.js Express/Connect 中,有没有办法将 session 设置为无限大?

javascript - JS中如何获取元素的实际宽度?

python - 从字符串开头删除连续字符

javascript - 正则表达式从字符串中获取所有 JavaScript 变量名称和值