开发者

Javascript Regex with .test()

> var p = /abc/gi;
> var s = &qu开发者_如何学Pythonot;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


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?


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜