1

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

3
  • Why are these paths valid? Would there be other paths that would be valid? Can't you do it via whitelisting and strings? Commented Nov 3, 2016 at 19:14
  • I intend to use window.location.pathname then extract only the main path from the fullpath Commented Nov 3, 2016 at 19:15
  • Those paths are all possibilities of my site Commented Nov 3, 2016 at 19:17

1 Answer 1

4

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly how I want, also thanks for warning not to use lookahead/behind :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.