Search code examples
javascriptregexquantifiers

Match last slash if there are at least nth occurrences


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?

http://www.regexr.com/393pm

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


Solution

  • You can use the following regex:

    \/.*?\/.*(\/)
    

    Here you have working example:

    http://regex101.com/r/xT3pN1/2

    Regular expression visualization

    Debuggex Demo

    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:

    http://regex101.com/r/xT3pN1/3