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

Viewed 47

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:

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

But I'm only getting the abc.

2 Answers

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

An alternative without a lookbehind, using an alternation and a capture group checking the value of group 1 in the callback of Array.from

If there is a group value, then return it, else return the match.

\/(\w+)|^\w+(?=\/)

Regex demo

const regex = /\/(\w+)|^\w+(?=\/)/g;
[
  "/abc/def/ghi?foo=bar",
  "/abc/xyz",
  "abc/xyz",
  "abc/xyz/",
  "abc",
].forEach(s => console.log(
  Array.from(s.matchAll(regex), m => m[1] ? m[1] : m[0])));

Or excluding the / and the ?

const regex = /\/([^\/?]+)|^[^\/?]+(?=\/)/g;
[
  "/abc/def/ghi?foo=bar",
  "/abc/xyz",
  "abc/xyz",
  "abc/xyz/",
  "abc",
].forEach(s => console.log(
  Array.from(s.matchAll(regex), m => m[1] ? m[1] : m[0])));

Related