Evan Dull
Evan Dull

Reputation: 108

Why does saving a JavaScript regular expression to a variable produce different results when invoking the .test() method?

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

Answers (1)

gen_Eric
gen_Eric

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

Related Questions