1

The following code:

var re = /^[A-Za-z_][A-Za-z0-9_]*$/g;
console.log('1', re.test('_1Test_TEST'));
console.log('2', re.test('test'));
console.log('3', re.test('test'));

console.log('4', /^[A-Za-z_][A-Za-z0-9_]*$/g.test('_1Test_TEST'));
console.log('5', /^[A-Za-z_][A-Za-z0-9_]*$/g.test('test'));
console.log('6', /^[A-Za-z_][A-Za-z0-9_]*$/g.test('test'));

outputs:

1 true
2 false
3 true
4 true
5 true
6 true

Why is case 2 failing (when case 3,5 & 6 are passing)?

Tried in both node 4.2 and 6.2

Ashley Coolman
  • 11,095
  • 5
  • 59
  • 81
  • 1
    Remove `g` and it should work. – Rajesh Jan 08 '17 at 14:39
  • 2
    reason is this http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results – Pavneet_Singh Jan 08 '17 at 14:39
  • 1
    it has to do with the value of `re.lastIndex`, and the seldom-used multiple call RX "iteration" behavior. if you put `re.lastIndex = 0;` in-between 1 and 2, it will work as-expected. It's easy to forget that RegExp instances are whole objects with properties (not just methods). `.exec()` makes good use of the "state" and `.compile()` can reset the state. – dandavis Jan 08 '17 at 14:40

0 Answers0