如何在JavaScript中提取URL的主机名部分是否有一个非常简单的方法从完整的URL开始:document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"并提取主机部分:aaa.bbb.ccc.com必须有一个可靠的JavaScript函数,但我找不到它。
3 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
有两种方法。第一个是这里的另一个答案的变体,但是这个解释了非默认端口:
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");}添加回答
举报
0/150
提交
取消
