How do I write a javascript function that takes one string argument which is a relative url as if it were a relative path such as you might see in a Linux bash script and combines it with the url of the current webpage to find a resource relative to the current webpage.
Examples of relative url:
- file2.html
- ./file2.html
- ../foo/file2.html
- ././file2.html
Example results:
-
basic case
- in webpage http://mysite.com/dir1/index.html
- relative url foo.html
- result http://mysite.com/dir1/foo.html
-
excess current directory dots (and local webpage)
- in webpage file:///C:/Users/Me/dir1/dir2/page.html
- relative url ././foo.html
- result file:///C:/Users/Me/dir1/dir2/foo.html
- or second preference file:///C:/Users/Me/dir1/dir2/././foo.html
-
parent directory (and some incidental excess dots, and another local webpage format)
- in webpage file:///C|/Users/Me/dir1/dir2/anotherpage.html
- relative url ./../././foo.html
- result file:///C:/Users/Me/dir1/foo.html
- or second preference file:///C:/Users/Me/dir1/dir2/./../././foo.html
Here is the working all-purpose solution:
DEMO: http://jsfiddle.net/h22SA/
Applying to the current page you should use: