Search code examples
javascripturlrelative-path

Window location one level up


This is my scenario:

I have my web page in folder:

http://www.example.com/example/index.html

I have media files in folder (one level up):

http://www.example.com/media/

and this files are linked in index.html like so: '../song1.mp3'

So when I read window.location.href from my web page I get this:

http://www.example.com/example/

But my media files are in location http://www.example.com/media/

Now I want to construct a download path for this media, but if I join window.location.href and media url I get this:

http://www.example.com/example/../song1.mp3

and I need to get this:

http://www.example.com/media/song1.mp3

what is the easiest way to manage this?

I am using javascript.


Solution

  • How about this:

    var filename = "../song1.mp3",
    
        domain   = "http://example.com/", // may be static or made by some black magic
    
        url      = domain + "media/" + filename.split("/").pop();
    

    So you just split your path with the ../-part, get the last element (would be "song1.mp3") and put it together to http://example.com/media/song1.mp3

    Here your have a live example.