我不确定为什么仅在变量而不是字符串中此评估会有所不同。我看不出任何逻辑。
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
答案 0 :(得分:3)
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
标志会记住最后一场比赛的位置。删除它以解决问题:
const numRegex = /hundred|thousand|million|billion|trillion/i;
Mozilla talks more about this:
sticky flag表示正则表达式通过尝试从RegExp.prototype.lastIndex开始的匹配来对目标字符串执行粘性匹配。