有没有一个简单的方法可以从一个完整的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向我提到这一点。
其他回答
Try
document.location.host
or
document.location.hostname
你可以连接位置协议和主机:
var root = location.protocol + '//' + location.host;
对于url,比如'http://stackoverflow.com/questions'它会返回'http://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。指派,但在我这行,那不重要。
您可以使用/来分割URL字符串
const exampleURL = “Https://exampleurl.com/page1/etc/etc” const URLsplit = exampleURL.split(“/”) console.log(网址拆分) console.log(URLsplit[2])
结果。exampleurl.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