views:

89

answers:

1

Regex test() is giving me issues in Firefox and Chrome, yet it works flawlessly in Opera and Safari.

troubled code:

var pattern = /(\s+(?!\$\w+)|(^(?!\$\w+)))/g;
if(pattern.test(String(id).replace(/\s+OR|AND\s+/g, ''))) {
 searchError("You suck.");
 return 1;
}

When you pass in white space, it blocks it every time. When you pass in something like '$a b' then it will work every other time in Firefox/Chrome. WEIRD.

FYI I'm still a regex n00b so please advise if my pattern sucks.

+6  A: 

It's a bug in the RegEx engine, a similar question with the same issue came up here.

From my answer to that question: It's a bug with the way regexes are implemented in ECMAScript 3, there's a great post on the details here.

The basics are a /regex/ with the g modifier doesn't reset correctly, so multiple .test() calls alternate between true and false if everyone should be true, every other calls successfully resets it.

Nick Craver
Oh snap. you guys are awesome. Thanks for the quick replies and helpful links (this was a tough one to search solutions for).
Jackson
@Jackson, if this answers your question (it should), then click the little check-mark, to the left -- to mark it as the accepted answer.
Brock Adams
@Brock Adams This must have skipped my attention. Thanks for the reminder.
Jackson