我们说我已经关注了网址。
/product
/product/1
/product/1/buy
/customer
/customer/1
/customer1/contact
我正在尝试使用正则表达式来获得以下匹配,因此我可以在其上运行switch语句。
/product
/customer
我已尝试过以下方法并尝试其他选项。
request.url.match(/^\/(.*)(\/?)/)
答案 0 :(得分:1)
答案 1 :(得分:1)
arr = [
'/product',
'/product/1',
'/product/1/buy',
'/customer',
'/customer/1',
'/customer/1/contact'
]
arr.forEach(a=>console.log(a.match(/^\/([^\/]*)/g)[0]));

这个解决方案怎么样?
答案 2 :(得分:0)
你很亲密!试试这个
/^\/(.*?)(\/|$)/
E.g。
/^\/(.*?)(\/|$)/.exec('/customer'); // ["/customer", "customer", ""]
/^\/(.*?)(\/|$)/.exec('/customer/asd'); // ["/customer/", "customer"]
/^\/(.*?)(\/|$)/.exec('/customer/asd/asd'); // ["/customer/", "customer", "/"]
<强>为什么强>
^\/
将匹配字符串的开头
(.*?)
将匹配任何内容(包括/
,?
使其非贪婪)。
最终\/
将使正则表达式回溯,直到/
之后找到(.*?)
或找到字符串末尾$
。