Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert relative path to absolute using JavaScript

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

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

It's always a relative path.

Let's think we know current path of the page, like http://site.com/stats/2012/, not sure how do I convert these relative paths to real ones?

We should get something like:

./some.css => http://site.com/stats/2012/some.css ./extra/some.css => http://site.com/stats/2012/extra/some.css ../../lib/slider/slider.css => http://site.com/lib/slider/slider.css 

No jQuery, only vanilla javascript.

like image 777
Jasper Avatar asked Feb 08 '13 19:02

Jasper


People also ask

How do you convert relative path to absolute path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

How do you find the absolute path of a node?

Use the path. resolve() method to get an absolute path of a file from a relative path in Node. js, e.g. path. resolve('./some-file.

What is a relative path Javascript?

A link that has an absolute path will tell the computer which server to go to and then all the folders that you have to drill down through to get to the target. A link that has a relative path will be written to tell the computer how to get from the folder with the currently viewed topic to the target.


2 Answers

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.

like image 173
Elad Avatar answered Sep 28 '22 03:09

Elad


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; } 
like image 21
allenhwkim Avatar answered Sep 28 '22 03:09

allenhwkim