0

This is my code:

var reIsNumeric = /[0-9]/g;
console.log(reIsNumeric.test(1));  // true
console.log(reIsNumeric.test(2));  // false
console.log(reIsNumeric.test(3));  // true
console.log(reIsNumeric.test(4));  // false

Does anyone know why only the odd numbers would return true? Am I losing my mind?

serverpunk
  • 10,665
  • 15
  • 61
  • 95

1 Answers1

2

Take the g out

var reIsNumeric = /[0-9]/;
console.log(reIsNumeric.test(1));  // true
console.log(reIsNumeric.test(2));  // true
console.log(reIsNumeric.test(3));  // true
console.log(reIsNumeric.test(4));  // true

http://jsfiddle.net/0tap3nfx/1/

The reason is because the g modifier is used to perform a global match (find all matches rather than stopping after the first match).

So basically the value that will return true is not what you would expect but the same regex as yours does work as expected see below.

var reIsNumeric = /[0-9]/g;
console.log(reIsNumeric.test(1));  // true
console.log(reIsNumeric.test(22));  // true
console.log(reIsNumeric.test(333));  // true
console.log(reIsNumeric.test(4444));  // true

http://jsfiddle.net/0tap3nfx/2/

GillesC
  • 10,647
  • 3
  • 40
  • 55