I need to replace the last slash if there are 3 or more occurrences. If we've a path like this "/foo/bar/"
, it should become "/foo/bar"
. But a path like "/foo/"
should not be touched.
I tried it with an escaped slash (\/
) and a quantifier ({3,}
):
/\/{3,}$/
However, this regular expression matches only slashes that are directly after another: "/foo/bar///"
Any ideas how I can solve this problem? Maybe with a positive/negative lookahead
?
To visualize:
"/foo/" => "/foo/"
"/foo/bar/" => "/foo/bar"
"/foo/bar/baz/" => "/foo/bar/baz"
Thanks to Fede, Avinash Raj & Amal Murali! Since performance matters, @Fede is the winner: http://jsperf.com/match-last-slash-if-there-are-at-least-nth-occurrences
You can use the following regex:
\/.*?\/.*(\/)
Here you have working example:
http://regex101.com/r/xT3pN1/2
If you want to keep it with content except the last slash, you can use this regex and reference the first group as \1
:
(\/.*?\/.*)(\/)
Check the working example with substitution: