如何在JavaScript中提取URL的主机名部分 [英] How to extract the hostname portion of a URL in JavaScript
问题描述
是否有一种非常简单的方法可以从完整的URL开始:
Is there a really easy way to start from a full URL:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
并提取只是主持人部分:
And extract just the host part:
aaa.bbb.ccc.com
必须有一个能够可靠地执行此操作的JavaScript函数,但我找不到它。
There's gotta be a JavaScript function that does this reliably, but I can't find it.
推荐答案
假设您有一个包含以下地址的页面: http://sub.domain.com/virtualPath/page.htm
。在页面代码中使用以下内容来获得这些结果:
suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm
. use the following in page code to achive those results:
-
window.location.host
:你将获得sub.domain.com:8080
或sub.domain.com:80
-
window.location.hostname
:你将获得sub.domain.com
-
window.location.protocol
:你将获得http:
-
window.location.port
:你将获得8080
或80
-
window.location.pathname
:你会得到/ virtualPath
-
window.location.origin
:你会得到http://sub.domain.com
*****
window.location.host
: you'll getsub.domain.com:8080
orsub.domain.com:80
window.location.hostname
: you'll getsub.domain.com
window.location.protocol
: you'll gethttp:
window.location.port
: you'll get8080
or80
window.location.pathname
: you'll get/virtualPath
window.location.origin
: you'll gethttp://sub.domain.com
*****
更新:关于.origin
*****作为 ref 表示, window.location.origin
的浏览器兼容性尚不清楚。我已经在chrome中检查了它并返回 http://sub.domain.com:port
如果端口不是80,那么 http ://sub.domain.com
如果端口是80。
***** As the ref states, browser compatibility for window.location.origin
is not clear. I've checked it in chrome and it returned http://sub.domain.com:port
if the port is anything but 80, and http://sub.domain.com
if the port is 80.
特别感谢@torazaburo向我提及。
这篇关于如何在JavaScript中提取URL的主机名部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!