Javascript regex matching string ending with incompatible number

I have the following regex patterns that match all 'act' that end with numbers in the list of urls.

Regular expression pattern /\/ch(\d+)\/act(\d+)/gi

Javascript Code

 pageSrc[1] = "../ch01/index.html"; pageSrc[2] = "../ch01/act01/1.html"; pageSrc[3] = "../ch01/act01/2.html"; pageSrc[4] = "../ch01/act02/1.html"; pageSrc[5] = "../ch01/act02/2.html"; pageSrc[6] = "../ch01/actx/1.html"; var pattern = /\/ch(\d+)\/act(\d+)/gi; for(var i=0; i<pageSrc.length; ++i){ var hasAct = pattern.test(pageSrc[i]); console.log(hasAct); } 

Expected Results and Actual Results

 | String | Expected Result | Actual Result | | pageSrc[1] | false | false | | pageSrc[2] | true | true | | pageSrc[3] | true | *FALSE | | pageSrc[4] | true | true | | pageSrc[5] | true | *FALSE | | pageSrc[6] | false | false | 

Not sure why pageSrc[3] will not return true . I used the regEx test on gskinner.com and it worked fine, here is the link http://gskinner.com/RegExr/?344ap

Can someone help me take a look, please? thanks in advance!

+4
source share
2 answers

Remove flag g . From the RegExp.test documentation:

As with exec (or in conjunction with it), test , called several times in the same instance of the global regular expression, will pass by the previous match.

You do not need a global search when reusing such a template.

 > var pageSrc = []; > pageSrc[1] = "../ch01/index.html"; pageSrc[2] = "../ch01/act01/1.html"; pageSrc[3] = "../ch01/act01/2.html"; pageSrc[4] = "../ch01/act02/1.html"; pageSrc[5] = "../ch01/act02/2.html"; pageSrc[6] = "../ch01/actx/1.html"; var pattern = /\/ch(\d+)\/act(\d+)/i; for(var i=0; i<pageSrc.length; ++i){ var hasAct = pattern.test(pageSrc[i]); console.log(i, hasAct); } 0 false 1 false 2 true 3 true 4 true 5 true 6 false 
+3
source

You use /g . Remove this flag to make it work.

The g flag causes the regular expression to start with pattern.lastIndex (the index where the previous match ended) until it fails, and then starts at 0.

+3
source

Source: https://habr.com/ru/post/1469134/


All Articles