Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Javascript RegExp behavior [duplicate]

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)

like image 887
Dave Avatar asked Mar 21 '13 23:03

Dave


2 Answers

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.

like image 127
Explosion Pills Avatar answered Oct 08 '22 17:10

Explosion Pills


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?

like image 24
jfriend00 Avatar answered Oct 08 '22 18:10

jfriend00