I need to build a router, that routes a REST request to a correct controller and action. Here some examples:
POST /users
GET /users/:uid
GET /users/search&q=lol
GET /users
GET /users/:uid/pictures
GET /users/:uid/pictures/:pid
It is important to have a single regular expression and as good as possible since routing is essential and done at every request.
we first have to replace : (untill end or untill next forward slash /) in the urls with a regex, that we can afterwards use to validate the url with the request url.
How can we replace these dynamic routings with regex? Like search for a string that starts with ":" and end with "/", end of string or "&".
This is what I tried:
var fixedUrl = new RegExp(url.replace(/\\\:[a-zA-Z0-9\_\-]+/g, '([a-zA-Z0-0\-\_]+)'));
For some reason it does not work. How could I implement a regex that replaces :id with a regex, or just ignores them when comparing to the real request url.
Thanks for help
I need to build a router, that routes a REST request to a correct controller and action. Here some examples:
POST /users
GET /users/:uid
GET /users/search&q=lol
GET /users
GET /users/:uid/pictures
GET /users/:uid/pictures/:pid
It is important to have a single regular expression and as good as possible since routing is essential and done at every request.
we first have to replace : (untill end or untill next forward slash /) in the urls with a regex, that we can afterwards use to validate the url with the request url.
How can we replace these dynamic routings with regex? Like search for a string that starts with ":" and end with "/", end of string or "&".
This is what I tried:
var fixedUrl = new RegExp(url.replace(/\\\:[a-zA-Z0-9\_\-]+/g, '([a-zA-Z0-0\-\_]+)'));
For some reason it does not work. How could I implement a regex that replaces :id with a regex, or just ignores them when comparing to the real request url.
Thanks for help
Share Improve this question edited Aug 4, 2012 at 2:28 Alan Haggai Alavi 74.3k19 gold badges104 silver badges128 bronze badges asked Aug 4, 2012 at 2:27 onlineracoononlineracoon 2,9705 gold badges48 silver badges66 bronze badges1 Answer
Reset to default 20I'd use :[^\s/]+
for matching parameters starting with colon (match :
, then as many characters as possible except /
and whitespace).
As replacement, I'm using ([\\w-]+)
to match any alphanumeric character, -
and _
, in a capture group, given you're interested in using the matched parameters as well.
var route = "/users/:uid/pictures";
var routeMatcher = new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)'));
var url = "/users/1024/pictures";
console.log(url.match(routeMatcher))