有没有一个简单的方法可以从一个完整的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函数能可靠地做到这一点,但我找不到。
当前回答
假设您有一个页面,其地址为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向我提到这一点。
其他回答
我的解决方案适用于所有浏览器,包括微软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;
}
}
您可以使用/来分割URL字符串
const exampleURL = “Https://exampleurl.com/page1/etc/etc” const URLsplit = exampleURL.split(“/”) console.log(网址拆分) console.log(URLsplit[2])
结果。exampleurl.com
有两种方法。第一个答案是另一个答案的变体,但这个答案说明了非默认端口:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
但我更喜欢这个更简单的方法(适用于任何URI字符串):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
使用文档。位置对象及其主机或主机名属性。
alert(document.location.hostname); // alerts "stackoverflow.com"
我知道这有点晚了,但我用一些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。指派,但在我这行,那不重要。