有没有一个简单的方法可以从一个完整的URL开始:

document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"

只提取主部分:

aaa.bbb.ccc.com

肯定有JavaScript函数能可靠地做到这一点,但我找不到。


当前回答

检查:

alert(window.location.hostname);

这将返回主机名www.domain.com

and:

window.location.host

将返回域名与端口如www.example.com:80

为完整的参考检查Mozilla开发者网站。

其他回答

假设您有一个页面,其地址为http://sub.domain.com/virtualPath/page.htm。

使用下面的页面代码来实现这些结果:

Property Result
window.location.host sub.domain.com:8080 or sub.domain.com:80
window.location.hostname sub.domain.com
window.location.protocol http:
window.location.port 8080 or 80
window.location.pathname /virtualPath
window.location.origin http://sub.domain.com (Might include :port too*****)

更新:关于.origin

*****正如引用所述,window.location.origin的浏览器兼容性并不清楚。我在chrome中检查了它,如果端口不是80,它返回http://sub.domain.com:port,如果端口是80,则返回http://sub.domain.com。

特别感谢@torazaburo向我提到这一点。

Try

document.location.host

or

document.location.hostname

我想具体说明一些事情。如果有人想要得到完整的url路径像我需要的,可以使用:

var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;

我知道这有点晚了,但我用一些ES6语法创建了一个干净的小函数

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

它也可以用ES5写成

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

IE当然不支持Object。指派,但在我这行,那不重要。

Regex提供了更大的灵活性。

    //document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
    //1.
     var r = new RegExp(/http:\/\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com

    //2. 
     var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf