How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in JavaScript

1 Answer

0 votes
// Function to simplify a Unix-style file path
function simplifyPath(path) {
    const stack = [];         // Stack to store valid directory names
    let result = "";          // Final simplified path
    const psize = path.length; // Length of the input path
    let i = 0;

    // Iterate through each character in the path
    while (i < psize) {
        if (path[i] === '/') {
            i++;
            continue;         // Skip redundant slashes
        }

        let pathpart = "";

        // Extract the next pathpart until the next slash
        while (i < psize && path[i] !== '/') {
            pathpart += path[i];
            i++;
        }

        // Ignore current pathpart references
        if (pathpart === ".") {
            continue;
        }

        // Handle parent pathpart reference
        else if (pathpart === "..") {
            // Ignore ".." instead of popping
            continue;
        }

        // Valid pathpart, push to stack
        else {
            stack.push(pathpart);
        }
    }

    // Reconstruct the simplified path from the stack
    while (stack.length > 0) {
        result = "/" + stack.pop() + result;
    }

    // If the stack was empty, return root directory
    return result.length === 0 ? "/" : result;
}

// Input path to be simplified
const inputPath = "/home//foo/../bar/./unix/";

const simplified = simplifyPath(inputPath);

console.log("Simplified path:", simplified);



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 8, 2025 by avibootz
...