有没有一个简单的方法可以从一个完整的URL开始:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
只提取主部分:
aaa.bbb.ccc.com
肯定有JavaScript函数能可靠地做到这一点,但我找不到。
有没有一个简单的方法可以从一个完整的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开发者网站。
其他回答
您可以使用/来分割URL字符串
const exampleURL = “Https://exampleurl.com/page1/etc/etc” const URLsplit = exampleURL.split(“/”) console.log(网址拆分) console.log(URLsplit[2])
结果。exampleurl.com
让我们假设你有这样的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
use
window.location.origin
对于:“http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah”
你会得到:http://aaa.bbb.ccc.ddd.com/
检查:
alert(window.location.hostname);
这将返回主机名www.domain.com
and:
window.location.host
将返回域名与端口如www.example.com:80
为完整的参考检查Mozilla开发者网站。
我知道这有点晚了,但我用一些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。指派,但在我这行,那不重要。