Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I get this behavior in both Chrome (Developer Tools) and Firefox (Firebug). Note the regex test returns alternating true/false values:

> var re = /.*?bl.*gr.*/gi;
undefined
> re
/.*?\bbl.*\bgr.*/gi
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false

However, testing the same regex as a literal:

> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true

I can't explain this and it's making debugging very difficult. Can anyone explain this behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
683 views
Welcome To Ask or Share your Answers For Others

1 Answer

/g (global) regexps will do that, yes.

See this question.

When you write a literal, you're getting a new regexp object every time, so losing the lastIndex state associated with the old object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...