有没有一个简单的方法可以从一个完整的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。指派,但在我这行,那不重要。

其他回答

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

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

结果。exampleurl.com

还有另一个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;

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

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

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

假设您有一个页面,其地址为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向我提到这一点。