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?
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?
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/etimaprotocol: http:hostname: jsbin.comhost: jsbin.comport:pathname: /etimasearch: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;
}
You might find http://blog.stevenlevithan.com/archives/parseuri / http://stevenlevithan.com/demo/parseuri/js/ interesting