views:

85

answers:

3

My url on a page is like:

http://www.example.com/dir1/file.html?a=1

I need to extract:

http://www.example.com

how can I do this in javascript?

+2  A: 
document.location.protocol + '//'+document.domain
Ninja Dude
...which will break if there's ever a port specified. :-)
T.J. Crowder
there is a port specified!
Blankman
+12  A: 

The window.location is an object with useful properties for this, details in this JSBin.

For that JSBin URL (http://jsbin.com/etima), here's what you see (with some irrelevancies removed):

  • href: http://jsbin.com/etima
  • protocol: http:
  • hostname: jsbin.com
  • host: jsbin.com
  • port:
  • pathname: /etima
  • search:
  • hash:

So basically, combine the protocol, the hostname, and the port if any:

var loc, result;
loc = window.location;
result = loc.protocol + "//" + loc.hostname;
if (loc.port) {
    result += ":" + loc.port;
}
T.J. Crowder