简体   繁体   中英

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']

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

Please guide Thanks everyone

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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