3 lines in JavaScript using regex

  • 0
    var simplifyPath = function(path, p = 'dummy') {
        path = path.replace(/\/{2,}/g, '/').replace(/(\/\.(?=\/|$)|\/$)/g, '');
        while (path !== (p = path.replace(/(^.*?)((?:\/\.\.(?=\/|$))+)/, (match, dirs, dd) => dirs.replace(new RegExp(`(\\/[^\\/]+){0,${dd.length / 3}}$`), '')))) path = p;
        return path || '/';
    1. Take care of redundant slashes and single dots.
    2. For directories preceding double dots, replace the last n directories according to the number of double dots. Positive lookahead (?=\/|$) takes care of corner cases such as valid directories prefixed by dots.

    See this solution by @linfongi for a cleaner approach.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.