Convert relative path to absolute using JavaScript

后端 未结 11 1579
误落风尘
误落风尘 2020-11-28 05:15

There\'s a function, which gives me urls like:

./some.css
./extra/some.css
../../lib/slider/slider.css

It\'s always a relative path.

<
11条回答
  •  余生分开走
    2020-11-28 05:38

    This from MDN is unbreakable!

    /*\
    |*|
    |*|  :: translate relative paths to absolute paths ::
    |*|
    |*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
    |*|
    |*|  The following code is released under the GNU Public License, version 3 or later.
    |*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
    |*|
    \*/
    
    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);
    }
    

    Sample usage:

    /* Let us be in /en-US/docs/Web/API/document.cookie */
    
    alert(location.pathname);
    // displays: /en-US/docs/Web/API/document.cookie
    
    alert(relPathToAbs("./"));
    // displays: /en-US/docs/Web/API/
    
    alert(relPathToAbs("../Guide/API/DOM/Storage"));
    // displays: /en-US/docs/Web/Guide/API/DOM/Storage
    
    alert(relPathToAbs("../../Firefox"));
    // displays: /en-US/docs/Firefox
    
    alert(relPathToAbs("../Guide/././API/../../../Firefox"));
    // displays: /en-US/docs/Firefox
    

提交回复
热议问题