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

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

只提取主部分:

aaa.bbb.ccc.com

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


当前回答

我知道这有点晚了,但我用一些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。指派,但在我这行,那不重要。

其他回答

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

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

use

window.location.origin

对于:“http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah”

你会得到:http://aaa.bbb.ccc.ddd.com/

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

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

您可以使用/来分割URL字符串

const exampleURL = “Https://exampleurl.com/page1/etc/etc” const URLsplit = exampleURL.split(“/”) console.log(网址拆分) console.log(URLsplit[2])

结果。exampleurl.com

接受的答案并没有为我工作,因为我希望能够与任何任意url的工作,而不仅仅是当前页面的url。

看一下URL对象:

var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol;  // "http:"
url.hostname;  // "aaa.bbb.ccc.com"
url.pathname;  // "/asdf/asdf/sadf.aspx"
url.search;    // "?blah"