JAVASCRIPT

Standardizing File Paths: Replacing Multiple Slashes

Clean up and normalize messy file or URL paths by replacing any sequence of two or more consecutive forward slashes with a single slash, ensuring consistent and valid path structures.

function normalizePath(path) {
    // Replace multiple consecutive slashes with a single slash
    let cleanedPath = path.replace(/\/\/+/g, '/');
    // And remove trailing slash if not root "/"
    if (cleanedPath.length > 1 && cleanedPath.endsWith('/')) {
        cleanedPath = cleanedPath.slice(0, -1);
    }
    return cleanedPath;
}

console.log(normalizePath("path///to//file.txt"));     // Expected: "path/to/file.txt"
console.log(normalizePath("/data//images///test/"));   // Expected: "/data/images/test"
console.log(normalizePath("///root"));                 // Expected: "/root"
console.log(normalizePath("/"));                       // Expected: "/"
How it works: This JavaScript snippet defines a function `normalizePath` that uses a regular expression `/\/\/+/g` to replace any occurrence of two or more consecutive forward slashes `//+` with a single slash `/`. This helps standardize file or URL paths. An additional check removes a trailing slash if the path is not just `/`, providing a clean, consistent path.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs