Skip to main content

Translates relative paths to absolute paths.

/**
 * Translate relative paths to absolute paths
 *
 * @param {String} sRelPath The relative path.
 * @return {String} The relative path converted to absolute path.
 */
function relPathToAbs(sRelPath) {
    var nUpLn, sDir = "",
        sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));

    for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
        nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
        sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
    }

    return sDir + sPath.substr(nStart);
}

//
// Usage
//

/* Let us be in /en-US/docs/Web/API/document.cookie */

console.log(location.pathname);
// displays: /en-US/docs/Web/API/document.cookie

console.log(relPathToAbs("./"));
// displays: /en-US/docs/Web/API/

console.log(relPathToAbs("../Guide/API/DOM/Storage"));
// displays: /en-US/docs/Web/Guide/API/DOM/Storage

console.log(relPathToAbs("../../Firefox"));
// displays: /en-US/docs/Firefox

console.log(relPathToAbs("../Guide/././API/../../../Firefox"));
// displays: /en-US/docs/Firefox