8
> var p = /abc/gi;
> var s = "abc";
> p.test(s);
  true
> p.test(s);
  false;

When I run this code on console of Chrome I Have this output above. Each time I call .test() I get a different value. Someone could explain to me why this happens? thanks

1

3 Answers 3

9

The behavior is due to the "g" modifier, i.e. matches three times, no match the fourth time:

> var p = /a/gi;
> var s = "aaa";
> p.test(s)
true
> p.test(s)
true
> p.test(s)
true
> p.test(s)
false

See similar question: Why RegExp with global flag in Javascript give wrong results?

Sign up to request clarification or add additional context in comments.

Comments

5

The g flag causes the RegExp literal your using to track the matches LastIndex

If you were to;

print( p.test(s), p.lastIndex )
print( p.test(s), p.lastIndex )

You would see

true,3
false,0

So the 2nd test fails as there is no incremental match from the 1st.

Comments

2

It's because of the /g flag. Every consecutive search starts from the character last matched in the previous search. In your case, in the second run it starts from the end of the string and returns false. The third time it starts from the beginning again. And so forth.

Also, take a look at this question: Why RegExp with global flag in Javascript give wrong results?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.