12

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

0

4 Answers 4

9

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.

5
  • will it keep tract of the last found index across different test() calls Mar 25, 2013 at 8:16
  • @ArunPJohny I don't think it can ever make sense to use the 'g' flag with the test function. Mar 25, 2013 at 8:21
  • I came across this problem while I was debugging this post, probably you can answer that too Mar 25, 2013 at 8:24
  • @ArunPJohny This seems the same problem, yes. I let you answer it. Mar 25, 2013 at 8:26
  • It is the same problem, because of the loops - only alternate results will be shown Mar 25, 2013 at 8:29
7

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;
3

Because you set the g modifier.

Remove it for your case.

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

It isn't a bug.

The g causes it to carry out the next attempted match for the substring, after the first match. And that is why it returns false in every even attempt.

First attempt: 
It is testing "Amanda Olmstead"

Second attempt:
It is testing "d" //match found in previous attempt (performs substring there)

Third attempt:
It is testing "Amanda Olmstead" again //no match found in previous attempt

... so on

MDN page for Regexp.exec states:

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property

MDN page for test states:

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.