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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With