0
var str = "^" + "/post/\d+" + "$";
var regex = new RegExp(str);
var flag = regex.test("/post/3333");

console.log(flag) // -> false
console.log(regex) // -> /^\/post\/d+$/

I'm expecting the result becomes true, but it results in false.

I think the problem is "\" is added automatically before "/" when RegExp instance is created.

How am I supposed to write in order to make it work?

2
  • 5
    When using RegExp constructor, you need to escape the backslashes twice. Once for the string and next for the regex. Use "^" + "/post/\\d+" Commented Jan 24, 2016 at 6:53
  • You printed out the value of regex--good debugging technique! Once you've done that, the problem is staring you in the face. You will see it says /^\/post\/d+$/. Note that the slashes have been transformed into \/ as they should, but the d has no preceding backslash! So it will just match an actual d! This would have been a great clue for you to start understanding what is happening. Commented Jan 24, 2016 at 7:38

2 Answers 2

1

You don't need the new RegExp constructor and string Here example

var regex = /post\/\d+$/;
var flag = regex.test("/post/3333");

I removed ^ flag, because regex will not work with this format of input "website/post/3333"

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

1 Comment

I need new RegExp constructor because I have a variable that I want to expand in regexp literal.
0

Here's a more specific regular expression to match the format of /post/####:

var regex = /\/post\/[0-9]+$/;
var flag = regex.test("/post/3333");

This will test for the string /post/ followed by one or more digits, occurring at the end of the line.

enter image description here

Likewise:

var regex = /\/post\/[0-9]{4}$/;
var flag = regex.test("/post/3333");

will test for the string /post/ followed by 4 digits, occurring at the end of the line.

enter image description here

2 Comments

The 2nd image says "3 times" intead of 4, is that intentional?
Yes, it's 3 times in addition to the first time. So it matches a single number once, then 3 more times. It is confusing upon first glance.

Your Answer

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