Javascript regex.match broken?

I promise you that I am not lying. There is one strange line in this usercript. His

if(rePrv.test(h)||rePrv.test(h)) 

Now, if I only have if(rePrv.test(h)) , I sometimes get false (wrong). However, with || I get the right results. It blows my brain. What's happening? Can someone explain? This happens under firefox 8, 11 (portable) and chrome 17.0.

This is my user code.

 // ==UserScript== // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js // ==/UserScript== var re=/\/?docs\/\d+/gi; var rePrv=/\/?docs\/\d+\/private/gi; var prvls=""; var publs=""; $('a').each(function(i, e){ var h = $(this).attr('href'); if(h==undefined) return; if(re.test(h)){ if(rePrv.test(h)||rePrv.test(h)){ prvls+="http://www.domain.com/"+h+"<br/>\n"; } else { publs+="http://www.domain.com/"+h+"<br/>\n"; } } }); 
+3
firefox google-chrome regex
source share
1 answer

Each instance of RegExp has an internal state , e. d. lastIndex , which indicates the index from which to start the next match. If you call exec or any other method that uses exec internally as test , this state may change when using global matching. Therefore, calling test several times can give you different results with each call:

 var str = 'foobar foobar'; var re = /foo/g; alert(re.test(str) && re.lastIndex); // re.lastIndex === 3 alert(re.test(str) && re.lastIndex); // re.lastIndex === 10 
+4
source share

All Articles