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

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

只提取主部分:

aaa.bbb.ccc.com

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


当前回答

你可以连接位置协议和主机:

var root = location.protocol + '//' + location.host;

对于url,比如'http://stackoverflow.com/questions'它会返回'http://stackoverflow.com'

其他回答

我的解决方案适用于所有浏览器,包括微软Internet Explorer,不使用任何正则表达式,它的灵感来自Noah Cardoza和Martin Konecny的解决方案:

function getHostname(href) {
    if (typeof URL === 'object') {
        // workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
        var dummyNode = document.createElement('a');
        dummyNode.href = href;
        return dummyNode.hostname;
    } else {
        // Martin Konecny's solution
        return new URL(href).hostname;
    }
}

检查:

alert(window.location.hostname);

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

and:

window.location.host

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

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

use

window.location.origin

对于:“http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah”

你会得到:http://aaa.bbb.ccc.ddd.com/

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

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

假设您有一个页面,其地址为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向我提到这一点。