简体   繁体   中英

How to get the http://www.blbah.com part of the url 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/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;
}
document.location.protocol + '//'+document.domain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM