Javascript routing regex

I need to build a router that sends a REST request to the right controller and action. Here are 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 one regular expression and the best possible, since routing is important and is performed on every request.

we must first replace: (to the end or to the next next slash /) in regular expression URLs, which we can subsequently use to validate the URL with the request URL.

How can we replace these dynamic routes with a regular expression? Like searching for a line that begins with ":" and ends with a "/", a line ends with or "&".

This is what I tried:

 var fixedUrl = new RegExp(url.replace(/\\\:[a-zA-Z0-9\_\-]+/g, '([a-zA-Z0-0\-\_]+)')); 

For some reason this does not work. How can I implement a regex that replaces: id with a regex or just ignores them compared to the real request URL.

thanks for the help

+6
source share
1 answer

I would use :[^\s/]+ to match parameters, starting with a colon (match : and then as many characters as possible except / and spaces).

As a replacement, I use ([\\w-]+) to match any alphanumeric character, - and _ , in the capture group, given that you are also interested in using the appropriate parameters.

 var route = "/users/:uid/pictures"; var routeMatcher = new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)')); var url = "/users/1024/pictures"; console.log(url.match(routeMatcher)) 
+12
source

Source: https://habr.com/ru/post/922099/


All Articles