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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With