1

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.

1
  • 1
    Do this in the console and see why: regex = RegExp("^\/r\/\d+\/$") Commented Oct 28, 2014 at 21:38

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Wow, that snippet stuff doesn't make the markup more readable... Or editable.
There is no need to escape /, it's not a special character. This should be enough: var regex = new RegExp("^/r/\\d+/$").
@Rudie: I'm not sure how much it's meant to, really; but yes: it's slightly awkward to play with it (unlike JS Fiddle, JS Bin et al).
@DavidThomas Why would it do that? The regex is between quotes, it is treated as a string.
@Gergo: finally edited the answer to remove the unnecessary escapes. Thanks! :)
2
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.

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.