有没有一个简单的方法可以从一个完整的URL开始:

document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"

只提取主部分:

aaa.bbb.ccc.com

肯定有JavaScript函数能可靠地做到这一点,但我找不到。


当前回答

有两种方法。第一个答案是另一个答案的变体,但这个答案说明了非默认端口:

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");
}

其他回答

Try

document.location.host

or

document.location.hostname

有两种方法。第一个答案是另一个答案的变体,但这个答案说明了非默认端口:

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");
}

我想具体说明一些事情。如果有人想要得到完整的url路径像我需要的,可以使用:

var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;

还有另一个hack我使用,从来没有看到任何StackOverflow响应: 使用图像的“src”属性将生成站点的完整基本路径。 例如:

var dummy = new Image;
dummy.src = '$';                  // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'

在http://domain.com/somesite/index.html这样的URL上, Root将被设置为http://domain.com/somesite/。 这也适用于localhost或任何有效的基本URL。

注意,这将导致对$ dummy映像的HTTP请求失败。 您可以使用现有的映像来避免这种情况,只需稍微修改代码。

另一种变体使用虚拟链接,对HTTP请求没有副作用:

var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;

不过,我并没有在每个浏览器上测试它。

我的解决方案适用于所有浏览器,包括微软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;
    }
}