RegExp.test () returns a different result for the same str depending on how (where?) It is called

I just noticed the strange behavior of JS that led to an annoying error.

Basically, I'm testing str with a RegExp object (.test () method) in an if statement. For the same line checked, if in my code I only have if, regexp.test () returns true, and it fits perfectly in the if.

The problem is that if I have else (and I need it), for some reason, for the same str check, regexp.test () returns false, and it goes into else ...

What is this behavior?

I have done many tests ...

TL / DR: for the same line tested on the same RegExp, if only the IF statement exists, regexp.test () returns true, but if I have else, it returns false.

some code 

I forgot to say that an error does not occur with all words ..

http://jsfiddle.net/zrwkU/13/

Write the word "armoire" in the text box and press enter. This jsfiddle has an "else return false" and nothing happens.

Remove the "else return false" in the searchdeeper function (if (regexp.test (verified)) {) and repeat the test. Now it goes to the if and msgbox popup.

+6
source share
2 answers

I think the only problem is that you have

 }else{ return false; } 

Actually you want

 }else{ continue; } 

to continue the outer loop for (var k in cats){ .

According to this update: http://jsfiddle.net/zrwkU/14/

As an explanation, with your code, as soon as the test call fails, this is from the method you use using return false . By switching to continue , you continue to “search deeper” in other categories.

+2
source

/regex/g.lastIndex = 0

With templates that have the global flag 'g' , RegExp methods; test() and exec() keep track of the last place they agreed on and store that integer in a RegExp: lastIndex object. This index automatically advances as each match applies to any row. Note that both test() and exec() behave this way. As soon as any match fails, this last index property will automatically reset to zero. You can manually reset yourself to reset yourself too, and this undoubtedly looks like what you need to do here. Add a line to reset RegExp.lastIndex like this:

 if (regexp != null){ regexp.lastIndex = 0; if (regexp.test(tested)){ alert('ok'); regexp.lastIndex = 0; var res = regexp.exec(tested); tested = tested.replace(res, '<span class="underlined">' + res + '</span>'); }else{ return false; } } 

Here is another solution that avoids this issue with the latest index. Instead, it uses the String.match() method:

A String.match() alternative:

 if (regexp != null){ if (tested.match(regexp)){ alert('ok'); regexp.lastIndex = 0; var res = tested.match(regexp); tested = tested.replace(res, '<span class="underlined">' + res + '</span>'); }else{ return false; } } 
+15
source

All Articles