Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex: How to get all strings between slashes from URL pathname?

How to get all strings between slashes from URL pathname until first interrogation mark if any using regex?

For instance, I can have:

/abc/def/ghi?foo=bar → ['abc','def','ghi']
/abc/xyz             → ['abc','xyz']
abc/xyz              → ['abc','xyz']
abc/xyz/             → ['abc','xyz']

I tried this javascript code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'/abc/def/ghi?foo=bar'.match(/\w+/)

But I’m only getting the abc.

>Solution :

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex with look around assertions:

/(?<=^|\/)[^\/?]+(?=[\/?]|$)/gm

RegEx Demo

RegEx Breakup:

  • (?<=^|\/): Lookbehind to assert presence of line start or / at previous position
  • [^\/?]+: Match 1+ of any char that is not / and ?
  • (?=[\/?]|$): Lookahead to assert presence of line end or / or ?` at next position
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading