Strange truth test results
filter = /rob/gi
>> /rob/gi
filter.test('hey')
>> false
filter.test('rob')
>> true
true && filter.test('rob');
>> false
true && filter.test('rob') ;
>> true
(true && filter.test('rob'));
>> false
(true && filter.test('rob')) ;
>> true
Reproducible in Firefox and Chrome
That's because .test
behaves as .exec()
and maintains state (position) between calls
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.
So for the 'rob'
input it matches it. Then on the second call it tries to match whatever left after the first match: it's an empty string, so it fails and rewinds.
To see it in action try to match 'robrobrob'
- there will be 3 true
followed by false
.
References:
UPD:
g
modified (credits to Barmar)