1

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:

  1. basic case

  2. 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
  3. 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

3 Answers 3

1

You can try URI js library

Try relativeTo, absoluteTo functions there.

For example:

var uri = new URI("../../foo.html");
var newUri = uri.absoluteTo("file://C:/Users/Me/dir1/dir2/page.html"); 
// newUri == "file://C:/Users/Me/foo.html"
1

If you know that accessing the href property of an anchor always gives you the absolute URL, you can simply create a temporary one and read the property:

function to_absolute_url(relative) {
    var a = document.createElement('a');
    a.href = relative;
    return a.href;
}

This of course works only if the URL you want to complete against is always the URL of the current page.

DEMO

0

Here is the working all-purpose solution:

function makePath(path, rel) {
    path = path.substring(0, path.lastIndexOf("/") + 1) + rel;
    var dirs = path.split("/");
    var result = [];
    for (var i = 0; i < dirs.length; i++) {
        if (dirs[i] == ".") continue;
        if (dirs[i] == "..") result.pop();
        else result.push(dirs[i]);
    }
    return result.join("/");
}

​DEMO: http://jsfiddle.net/h22SA/

Applying to the current page you should use:

makePath(location.href, "././foo.html")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.