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.
This should do it:
This from MDN is unbreakable!
Sample usage:
The proposed and accepted solution does not support server relative URLs and does not work on absolute URLs. If my relative is /sites/folder1 it won't work for example.
Here is another function that supports full, server relative or relative URLs as well as ../ for one level up. It is not perfect but covers a lot of options. Use this when your base URL is not the current page URL, otherwise there are better alternatives.
Hope this helps. It was really frustrating not to have this basic utility available in JavaScript.
Javascript will do it for you. There's no need to create a function.
But if you need it as a function:
Update: Simpler version if you need the full absolute path:
I found a very simple solution to do this while still supporting IE 10 (IE doesn't support the URL-API) by using the History API (IE 10 or higher). This solution works without any string manipulation.
history.replaceState()
won't trigger browser navigation, but will still modifydocument.location
and supports relative aswell as absolute paths.The one drawback of this solution is that if you are already using the History-API and have set a custom state with a title, the current state's title is lost.
I had to add a fix to the accepted solution because we can have slashes after # in our angularjs navigation.