4

I am not sure why this evaluation differs when it is only in a variable, versus a string. I don't see any logic.

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
Ivar
  • 6,138
  • 12
  • 49
  • 61
Yu Mad
  • 828
  • 2
  • 12
  • 29
  • The issue is the order, not whether it's a variable or not. You can copy the first console log, and will get the same results. You are reusing the regex, and due to the `g` flag, the regex' `lastIndex` gets updated, and stays changed in any subsequent calls. – ASDFGerte Dec 23 '19 at 22:17
  • 1
    @Ivar thanks, I couldn't find it… – Bergi Dec 23 '19 at 22:29

1 Answers1

3

isNum is returning false when it's called a second time on the same string. Change the order and see the same thing:

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

The g flag remembers where the last match was. Remove it to fix the problem:

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.

Anonymous
  • 11,748
  • 6
  • 35
  • 57