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?
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"
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.