Convert relative path to absolute using JavaScript
The most simple, efficient and correct way to do so it to just use URL api.
new URL("http://www.stackoverflow.com?q=hello").href;
//=> "http://www.stackoverflow.com/?q=hello"
new URL("mypath","http://www.stackoverflow.com").href;
//=> "http://www.stackoverflow.com/mypath"
new URL("../mypath","http://www.stackoverflow.com/search").href
//=> "http://www.stackoverflow.com/mypath"
new URL("../mypath", document.baseURI).href
//=> "https://stackoverflow.com/questions/mypath"
Performance wise, this solution is on par with using string manipulation and twice as fast as creating a
tag.
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;
}