Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript routing regex

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

like image 533
onlineracoon Avatar asked Aug 04 '12 02:08

onlineracoon


People also ask

What is JavaScript routing?

A Javascript router is a key component in most frontend frameworks. It is the piece of software in charge to organize the states of the application, switching between different views.

Does regex work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags. In this section, we'll explore the different ways to write regular expressions while focusing on simple patterns, special characters, and flags.

How use regex in Express JS?

We can easily set up Regex for our Express Router by following these two points: To make our route match with a particular regular expression, we can put regex between two forward slashes like this /<routeRegex>/ Since every route contain /, so wherever we have to use / inside Regex, use a backslash \ / before it.

What is regex in JavaScript?

A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.


1 Answers

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))
like image 100
Imran Avatar answered Sep 16 '22 12:09

Imran