Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

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
...