I create a RegExp object (in JavaScript) to test for the presence of a number:
var test = new RegExp( '[0-9]', 'g' );
I use it like this
console.log( test.test( '0' ) ); // true
console.log( test.test( '1' ) ); // false - why?
The output of this is even more confusing:
console.log( test.test( '1' ) ); // true
console.log( test.test( '0' ) ); // false - why?
console.log( test.test( '1' ) ); // true
console.log( test.test( '2' ) ); // false - why?
console.log( test.test( '2' ) ); // true - correct, but why is this one true?
If I remove the g
qualifier, it behaves as expected.
Is this a bug as I believe it is, or some peculiar part of the spec? Is the g
qualifier supposed to be used this way? (I'm re-using the same expression for multiple tasks, hence having the qualifier at all)
Per documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test#Description
test
called multiple times on the same global regular expression instance will advance past the previous match.
You can confirm this behavior:
var test = new RegExp( '[0-9]', 'g' );
test.test('01'); //true
test.test('01'); //true
test.test('01'); //false
It doesn't make sense to use the g
flag if all you want is to confirm a single match against various strings.
Remove the 'g'
flag. When you use the 'g
' flag, it updates the lastIndex
property of the regex (preparing for a successive search on the same string) and then starts the next search from that index value (thus giving you a false reading on your next search).
Similar question and answer here: Why is Regex Javascript //g flag affecting state?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With