Artisan
Artisan

Reputation: 4112

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 [a-z].*(?=\/|\?), unfortunately it only matches string inside the last two

Please guide Thanks everyone

Upvotes: 1

Views: 17919

Answers (1)

Peter G
Peter G

Reputation: 2821

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

Upvotes: 4

Related Questions