Andy
Andy

Reputation: 950

Regex Confusion JavaScript

I've been trying to match the following the path below with a regex:

path = "/r/356363/"

that looks like:

regex = RegExp("^\/r\/\d+\/$")

However, whenever I run test, I do

regex.test(path)

which returns

false

Why doesn't the regex match the path?

To me the regex says, find a string that starts with a /r/, has atleast one digit after, and ends in a /.

I checked the regex in http://regex101.com/#javascript and it appears as a match which leads me more confused.

Upvotes: 1

Views: 37

Answers (2)

Greg
Greg

Reputation: 3568

RegExp("^\/r\/\d+\/$").test('/r/124/') === false

but if you use the regex literal writing:

/^\/r\/\d+\/$/.test('/r/124/') === true

While the forward slashes need to be escaped in the literal version, they don't need to be in the object version. However, backward slashes need to be escaped in the object version (not in the literal version). So you could also have written:

RegExp("^/r/\\d+/$").test('/r/124/') === true

The issue is that you have used a syntax that works only with the literal version.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

The problem is you need to escape the escapes; the first \ escapes the following character in the string, you need a second \ to escape the subsequent \ for the RegExp itself:

var path = "/r/356363/",
    regex = RegExp("^\\/r\\/\\d+/$");
console.log(regex.test(path));

var path = "/r/356363/",
    regex = RegExp("^\\/r\\/\\d+\\/$");
console.log(regex.test(path));

Upvotes: 4

Related Questions