捕获网址的第一部分

时间:2020-12-24 10:29:04

Let's say I've following URLs.

假设我已经关注了网址。

/product
/product/1
/product/1/buy

/customer
/customer/1
/customer1/contact

I'm trying for a regular expression to get the following match so I can run a switch statement on it.

我正在尝试使用正则表达式来获得以下匹配,因此我可以在其上运行switch语句。

/product

/customer

I've tried the following and trying other options as well.

我尝试过以下内容并尝试其他选项。

request.url.match(/^\/(.*)(\/?)/)

3 个解决方案

#1


1  

arr = [
        '/product',
        '/product/1',
        '/product/1/buy',
        '/customer',
        '/customer/1',
        '/customer/1/contact'
      ]

arr.forEach(a=>console.log(a.match(/^\/([^\/]*)/g)[0]));

How about this solution?

这个解决方案怎么样?

#2


1  

Another option is to use split:

另一种选择是使用拆分:

var result = request.url.split("/")[1]; // result = product

Fiddle

#3


0  

You were close! Try this one

你很亲密!试试这个

/^\/(.*?)(\/|$)/

E.g.

/^\/(.*?)(\/|$)/.exec('/customer'); // ["/customer", "customer", ""]
/^\/(.*?)(\/|$)/.exec('/customer/asd'); // ["/customer/", "customer"]
/^\/(.*?)(\/|$)/.exec('/customer/asd/asd'); // ["/customer/", "customer", "/"]

Why
The ^\/ will match the start of the string.
The (.*?) will match anything after (including /, ? makes it non-greedy).
The final \/ will make the regex backtrack until / is found after the (.*?) or if the end of the string is found $.

为什么^ \ /将匹配字符串的开头。 (。*?)将匹配任何内容(包括/,?使其非贪婪)。最后的\ /将使正则表达式回溯直到/找到(。*?)之后或者如果找到字符串的末尾$。

#1


1  

arr = [
        '/product',
        '/product/1',
        '/product/1/buy',
        '/customer',
        '/customer/1',
        '/customer/1/contact'
      ]

arr.forEach(a=>console.log(a.match(/^\/([^\/]*)/g)[0]));

How about this solution?

这个解决方案怎么样?

#2


1  

Another option is to use split:

另一种选择是使用拆分:

var result = request.url.split("/")[1]; // result = product

Fiddle

#3


0  

You were close! Try this one

你很亲密!试试这个

/^\/(.*?)(\/|$)/

E.g.

/^\/(.*?)(\/|$)/.exec('/customer'); // ["/customer", "customer", ""]
/^\/(.*?)(\/|$)/.exec('/customer/asd'); // ["/customer/", "customer"]
/^\/(.*?)(\/|$)/.exec('/customer/asd/asd'); // ["/customer/", "customer", "/"]

Why
The ^\/ will match the start of the string.
The (.*?) will match anything after (including /, ? makes it non-greedy).
The final \/ will make the regex backtrack until / is found after the (.*?) or if the end of the string is found $.

为什么^ \ /将匹配字符串的开头。 (。*?)将匹配任何内容(包括/,?使其非贪婪)。最后的\ /将使正则表达式回溯直到/找到(。*?)之后或者如果找到字符串的末尾$。