简体   繁体   English

JavaScript RegEx匹配网址路径

[英]JavaScript RegEx to match url path

I have possible url paths as below 我有如下可能的网址路径

/articles
/payment
/about
/articles?page=1
/articles/hello-world

I would like to match only the main path of the url, expected matches: ['articles', 'payment', 'about', 'articles', 'articles'] 我只想匹配url的主要路径,即预期的匹配项: ['articles', 'payment', 'about', 'articles', 'articles']

So I tried to construct the JavaScript RegEx and came up with as nearest as I can [az].*(?=\\/|\\?) , unfortunately it only matches string inside the last two 因此,我尝试构建JavaScript RegEx并尽可能地提出[az].*(?=\\/|\\?) ,不幸的是,它仅与最后两个字符串匹配

Please guide Thanks everyone 请指导谢谢大家

https://regex101.com/r/A86hYz/1 https://regex101.com/r/A86hYz/1

/^\/([^?\/]+)/

This regex captures everything between the first / and either the second / or the first ? 此正则表达式捕获第一个/和第二个/或第一个之间的所有内容? if they exist. 如果存在。 This seems like the pattern you want. 这似乎是您想要的模式。 If it isn't, let me know and I'll adjust it as needed. 如果不是,请告诉我,我会根据需要进行调整。 Some simple adjustments would be capturing what's between every / as well as capturing the query parameters. 一些简单的调整将是捕获每个/之间的内容以及捕获查询参数。

For future reference, when writing regex, try to avoid the lookahead/behind unless you have to as they usually introduce bugs. 为了将来参考,在编写正则表达式时,请尽量避免先行/后退,除非您必须这样做,因为它们通常会引入错误。 It's easiest if you stick to using the regular operators. 如果您坚持使用常规运算符,这是最简单的。

To access the match, use the regex like this: 要访问匹配项,请使用正则表达式,如下所示:

var someString = '/articles?page=1';
var extracted = someString.match(/^\/([^?\/]+)/)[1]

or more generally 或更一般地

function getMainPath(str) {
    const regex = /^\/([^?\/]+)/;
    return str.match(regex)[1];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM