8

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

1 Answer 1

20

I'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))
Sign up to request clarification or add additional context in comments.

1 Comment

I think the underline ( _ ) is missing in ([\\w-]+) ?

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.