这个问题在这里已经有了答案:
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/