Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for selecting the first element of a path

Tags:

regex

path

My question is pretty simple, I would like to write a RegEx that does this:

/ -> /

/foo -> /foo

/foo/bar -> /foo

/foo/bar/baz -> /foo

I've tried this:

replace(/(\/[^\/]*)\/[^\/]*/, '$1')

But it returns the path, unmodified.

Does anyone know how to do?

like image 243
Naïm Favier Avatar asked Jun 19 '15 08:06

Naïm Favier


2 Answers

This should work:

/^\/[^\/]*/

It will match the start slash and all chars until another slash is found (excepting the 2nd slash)

'/test'.match(/^\/[^\/]+/)[0]

will return '/test'

'/test/asd'.match(/^\/[^\/]+/)[0]

will return '/test'

Strings that don't start with a slash will not match.

like image 88
Andrei Tătar Avatar answered Oct 05 '22 17:10

Andrei Tătar


To replace the entire string the regex should match it (entirely) so this is a regex you can use:

"/foo/bar/baz".replace(/(\/[^\/]*).*/, "$1")

it will capture a forward slash, followed by any non-forward slash symbol (exactly what you've done) and then .* will match anything until the end of the string (just to replace the entire string)

like image 41
Teneff Avatar answered Oct 05 '22 19:10

Teneff