RegEx to select the first element of the path
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 share
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 to share