I want to use jQuery to get the location and the first folder with window.location

user770252 picture user770252 · Jan 25, 2012 · Viewed 9.1k times · Source

I want to get the location and the first folder, like:

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

var $location = window.location.href;
alert ($location);

this returns

http://www.example.com/test/location-test.html

So I would like it to return everything up to "test/", so I only end up with:

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

Thanks in advance!

Answer

ShankarSangoli picture ShankarSangoli · Jan 25, 2012

You can try this.

var url = location.protocol + "//" + document.domain + "/" 
          + location.pathname.split('/')[1] + "/";