RegEx to select the first element of the 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 this?

+3


source to share


2 answers


This should work:

/^\/[^\/]*/

      

It will match the starting slash and all characters until another slash is found (other than the 2nd slash)

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

      



will return '/ test'

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

      

will return '/ test'

Lines that do not start with a forward slash will not match.

+5


source


To replace an entire string, a regex must match it (completely), so this is a regex you can use:

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

      



it will write a forward slash followed by any non-forward slash character (exactly what you did) and then .*

match anything to the end of the line (just to replace the entire string)

+1


source







All Articles