Convert relative path to absolute using JavaScript

后端 未结 11 1549
误落风尘
误落风尘 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:30

    I had to add a fix to the accepted solution because we can have slashes after # in our angularjs navigation.

    function getAbsoluteUrl(base, relative) {
      // remove everything after #
      var hashPosition = base.indexOf('#');
      if (hashPosition > 0){
        base = base.slice(0, hashPosition);
      }
    
      // the rest of the function is taken from http://stackoverflow.com/a/14780463
      // http://stackoverflow.com/a/25833886 - this doesn't work in cordova
      // http://stackoverflow.com/a/14781678 - this doesn't work in cordova
      var stack = base.split("/"),
          parts = relative.split("/");
      stack.pop(); // remove current file name (or empty string)
                   // (omit if "base" is the current folder without trailing slash)
      for (var i=0; i

提交回复
热议问题