regex.test() only works every other time Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of regex.test() only works every other time without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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|ANDs+/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.

Answer

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.

We are here to answer your question about regex.test() only works every other time - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji