Ben Usman
Ben Usman

Reputation: 8387

JavaScript: different results of regexp test inside and outside loop

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.

Upvotes: 3

Views: 200

Answers (2)

Paul Grime
Paul Grime

Reputation: 15104

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

Upvotes: 1

kol
kol

Reputation: 28708

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/))";

Upvotes: 1

Related Questions