Convert relative path to absolute using JavaScript

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

    Javascript will do it for you. There's no need to create a function.

    var link = document.createElement("a");
    link.href = "../../lib/slider/slider.css";
    alert(link.protocol+"//"+link.host+link.pathname+link.search+link.hash);
    
    // Output will be "http://www.yoursite.com/lib/slider/slider.css"
    

    But if you need it as a function:

    var absolutePath = function(href) {
        var link = document.createElement("a");
        link.href = href;
        return (link.protocol+"//"+link.host+link.pathname+link.search+link.hash);
    }
    

    Update: Simpler version if you need the full absolute path:

    var absolutePath = function(href) {
        var link = document.createElement("a");
        link.href = href;
        return link.href;
    }
    

提交回复
热议问题