2

I have this simple pattern that validate Time - 24 Hours Mode -

var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g; 

If i execute this pattern with .test() method twice i get two different values

Like This

CODE

console.log(patt.test('01:09')); // true
console.log(patt.test('01:09')); // false 

i have notice that if i do the following i get the same result :

var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g; 
console.log(patt.test('01:09')); // true

var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g; 
console.log(patt.test('01:09'));//true

Question i'll re-initiate the patt object as a work around in my case but i'm very curious to know what happens

Also i notice that patt object doesn't change after using it with test() Method

jsFiddle for those how want to prove something

Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • From the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test): *" As with `exec` (or in combination with it), `test` called multiple times on the same global regular expression instance will advance past the previous match."* – Felix Kling Jul 09 '13 at 16:43

1 Answers1

1

Remove the global flag. Currently it's searching at the end of your input string for the second time, where it won't find the pattern again. See docs for the lastIndex property.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375