0

Why is this regex not working properly ?

 new RegExp(/[a-z\d]/g).test('5');

The result is sometimes true and other time false. It keeps toggling between true/false

var regx = new RegExp(/[a-z\d]/g);

console.log(regx.test('5')) // true
console.log(regx.test('5')) // false
console.log(regx.test('5')) // true
console.log(regx.test('5')) // false

1 Answers1

0

It's because the result is looking again, from the start:
(the lastIndex property shows it: after first find lastIndex=== 1, but since string is has length 1, the next search/test is false, at the ende of the string it lastIndex is "reset" to 0)

var regx = new RegExp(/[a-z\d]/g);

console.log(regx.test('5'), regx.lastIndex) // true 1
console.log(regx.test('5'), regx.lastIndex) // false 0
console.log(regx.test('5'), regx.lastIndex) // true 1
console.log(regx.test('5'), regx.lastIndex) // false 0
winner_joiner
  • 12,173
  • 4
  • 36
  • 61