3

I'm iterating over links and chose what I need by regex.

var str = "http://([^.]*).time.com/($|(page/\d/))";
var reg = new RegExp(str); var arr = [], l = document.links;
for(var i=0; i<l.length; i++) {
console.log(l[i].href + '\t\t\t-' + reg.test(l[i].href)); 
}

>...
>http://newsfeed.time.com/page/3/           -false
>...

But:

/http:\/\/([^.]*).time.com\/($|(page\/\d\/))/.test('http://newsfeed.time.com/page/3/')
>true

What am I doing wrong? :) Thank you.

2
  • Why would you use a regexp constructor with a constant string? Just use a regexp literal like you used in the console. Commented Aug 27, 2013 at 22:21
  • On an unrelated note, you also need to escape the . characters in the regex. Again, it's two backslashes in string literals, one in regex literals. (Except that the first . doesn't need escaping because it's in a character class so the rules are different.) NB: Little things like this can sometimes compromise security. For example, if your code assumes that any URL matching this regex is trustworthy, a malicious person could circumvent it by registering the URL http://my-malicious-url-time.com/, which matches the regex as you've written it. Commented Aug 27, 2013 at 23:12

2 Answers 2

1

You need to escape the backslash in the string version of the regex (i.e. use \\d):

var str = "http://([^.]*).time.com/($|(page/\\d/))";

So:

var str = "http://([^.]*).time.com/($|(page/\\d/))";
var reg = new RegExp(str); var arr = [], l = ['http://newsfeed.time.com/page/3/'];
for(var i=0; i<l.length; i++) {
    console.log(l[i] + '\t\t\t-' + reg.test(l[i])); 
}

gives:

http://newsfeed.time.com/page/3/            -true
Sign up to request clarification or add additional context in comments.

Comments

1

You should escape the backslash in \d when you specify the regex in a string. This is not needed in a regex literal, that's why it works. So this line:

var str = "http://([^.]*).time.com/($|(page/\d/))";

should look like this:

var str = "http://([^.]*).time.com/($|(page/\\d/))";

Comments

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.