Javascript路由正则表达式 [英] Javascript routing regex

查看:108
本文介绍了Javascript路由正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个路由器,将REST请求路由到正确的控制器和操作。这里有一些例子:

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 "&".

这是我试过的:

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

由于某种原因,它不起作用。我如何实现用正则表达式替换:id的正则表达式,或者在与真实请求网址进行比较时忽略它们。

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.

感谢您的帮助

推荐答案

我使用:[^ \s /] + 来匹配参数,以...开头冒号(匹配,然后尽可能多的字符,除了 / 和空格)。

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))

这篇关于Javascript路由正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆