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

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

只提取主部分:

aaa.bbb.ccc.com

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


当前回答

让我们假设你有这样的url路径:

http://localhost:4200/landing?query=1#2

因此,你可以通过位置值为自己服务,如下所示:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

现在我们可以得出结论,你在寻找:

window.location.hostname

其他回答

让我们假设你有这样的url路径:

http://localhost:4200/landing?query=1#2

因此,你可以通过位置值为自己服务,如下所示:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

现在我们可以得出结论,你在寻找:

window.location.hostname

我的解决方案适用于所有浏览器,包括微软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;
    }
}

Try

document.location.host

or

document.location.hostname

use

window.location.origin

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

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

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