Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `pattern.test(name)` opposite results on consecutive calls [duplicate]

Why is this code returning first true, then false

var pattern = new RegExp("mstea", 'gi'), name = "Amanda Olmstead";

console.log('1', pattern.test(name));
console.log('1', pattern.test(name));

Demo: Fiddle

like image 797
Arun P Johny Avatar asked Mar 25 '13 08:03

Arun P Johny


2 Answers

g is for repeating searches. It changes the regular expression object into an iterator. If you want to use the test function to check your string is valid according to your pattern, remove this modifier :

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

The test function, contrary to replace or match doesn't consume the whole iteration, which lets it in a "bad" state. You should probably never use this modifier when using the test function.

like image 130
Denys Séguret Avatar answered Sep 20 '22 12:09

Denys Séguret


You don't want to use gi in combination with pattern.test. The g flag means that it keeps track of where you are running so it can be reused. So instead, you should use:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

console.log('1', pattern.test(name));
console.log('1', pattern.test(name));

Also, you can use /.../[flags] syntax for regex, like so:

var pattern = /mstea/i;
like image 20
Mark Ormston Avatar answered Sep 21 '22 12:09

Mark Ormston