Reputation: 108
Can someone explain why saving this regex to a variable produces alternating true and false values, but using the literal produces true every time? Am I missing something obvious here? I'm certainly not a regex expert, but this seems like odd behavior to me.
var exp = /[\^~\\><\|"]/g;
exp.test('<abc'); // true
exp.test('<abc'); // false
exp.test('<abc'); // true
exp.test('<abc'); // false
/[\^~\\><\|"]/g.test('<abc'); // true
/[\^~\\><\|"]/g.test('<abc'); // true
/[\^~\\><\|"]/g.test('<abc'); // true
/[\^~\\><\|"]/g.test('<abc'); // true
CodePen Demo (check the console)
Upvotes: 2
Views: 62
Reputation: 227270
This is because regular expression objects save their state, so when you call test again on the same object it tries to find the next match and fails.
From the docs:
test called multiple times on the same global regular expression instance will advance past the previous match.
In the last examples, you are creating a new regular expression each time, so it matches every time.
Upvotes: 4