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
.
CodePudding user response:
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 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