4

I have the following regex patterns that matches all the 'act' that ends with numbers within a list of URLs.

Regex 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);
}

The 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        |

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

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

2 Answers 2

3

Remove the g flag. From the RegExp.test documentation:

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

You don't want a global search when reusing a pattern like this.

> 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
Sign up to request clarification or add additional context in comments.

Comments

3

You are using /g. Remove that flag to make it work.

The g flag makes the regex start matching from pattern.lastIndex (the index where the previous match ended), until it fails, and then start at 0.

1 Comment

Thanks for replying, your solution works just as Matt's. Since i cannot mark 2 answers, i've up voted yours :) thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.