简体   繁体   English

如何在 JavaScript 中提取 URL 的主机名部分

[英]How to extract the hostname portion of a URL in JavaScript

Is there a really easy way to start from a full URL:是否有一种非常简单的方法可以从完整的 URL 开始:

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

And extract just the host part:并仅提取主机部分:

aaa.bbb.ccc.com

There's gotta be a JavaScript function that does this reliably, but I can't find it.必须有一个 JavaScript 函数可以可靠地执行此操作,但我找不到它。

suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm .假设您有一个具有以下地址的页面: http://sub.domain.com/virtualPath/page.htm use the following in page code to achive those results:在页面代码中使用以下内容来实现这些结果:

  • window.location.host : you'll get sub.domain.com:8080 or sub.domain.com:80 window.location.host :你会得到sub.domain.com:8080sub.domain.com:80
  • window.location.hostname : you'll get sub.domain.com window.location.hostname :你会得到sub.domain.com
  • window.location.protocol : you'll get http: window.location.protocol : 你会得到http:
  • window.location.port : you'll get 8080 or 80 window.location.port : 你会得到808080
  • window.location.pathname : you'll get /virtualPath window.location.pathname :你会得到/virtualPath
  • window.location.origin : you'll get http://sub.domain.com ***** window.location.origin : 你会得到http://sub.domain.com *****

Update: about the .origin更新:关于 .origin

***** As the ref states, browser compatibility for window.location.origin is not clear. ***** 正如ref所述, window.location.origin浏览器兼容性尚不清楚。 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.我已经在Chrome检查,它返回http://sub.domain.com:port如果端口是什么,但80和http://sub.domain.com如果端口为80。

Special thanks to @torazaburo for mentioning that to me.特别感谢@torazaburo 向我提及这一点。

You could concatenate the location protocol and the host:您可以连接位置协议和主机:

var root = location.protocol + '//' + location.host;

For a url, let say 'http://stackoverflow.com/questions' , it will return 'http://stackoverflow.com'对于 url,假设'http://stackoverflow.com/questions' ,它将返回'http://stackoverflow.com'

The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.接受的答案对我不起作用,因为希望能够使用任何任意 url,而不仅仅是当前页面的 URL。

Take a look at the URL object :看看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"

使用document.location对象及其hosthostname属性。

alert(document.location.hostname); // alerts "stackoverflow.com"

There are two ways.有两种方法。 The first is a variant of another answer here, but this one accounts for non-default ports:第一个是此处另一个答案的变体,但这个解释了非默认端口:

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

But I prefer this simpler method (which works with any URI string):但我更喜欢这种更简单的方法(适用于任何 URI 字符串):

function getRootUrl(url) {
  return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}

Try尝试

document.location.host

or要么

document.location.hostname

use采用

window.location.origin窗口.位置.原点

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

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

Check this:检查这个:

alert(window.location.hostname);

this will return host name as www.domain.com这将返回主机名作为www.domain.com

and:和:

window.location.host

will return domain name with port like www.example.com:80将返回带有端口的域名,如www.example.com:80

For complete reference check Mozilla developer site.有关完整的参考,请查看Mozilla 开发人员站点。

There is another hack I use and never saw in any StackOverflow response : using "src" attribute of an image will yield the complete base path of your site.我使用的另一个技巧在任何 StackOverflow 响应中从未见过:使用图像的“src”属性将生成您网站的完整基本路径。 For instance :例如 :

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

On an URL like http://domain.com/somesite/index.html , root will be set to http://domain.com/somesite/ .在像http://domain.com/somesite/index.html这样的 URL 上, root将被设置为http://domain.com/somesite/ This also works for localhost or any valid base URL.这也适用于 localhost 或任何有效的基本 URL。

Note that this will cause a failed HTTP request on the $ dummy image.请注意,这将导致对$虚拟图像的 HTTP 请求失败。 You can use an existing image instead to avoid this, with only slight code changes.您可以使用现有图像来避免这种情况,只需稍微更改代码即可。

Another variant uses a dummy link, with no side effect on HTTP requests :另一种变体使用虚拟链接,对 HTTP 请求没有副作用:

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

I did not test it on every browser, though.不过,我没有在每个浏览器上测试它。

I would like to specify something.我想说明一些事情。 If someone want to get the whole url with path like I need, can use:如果有人想像我需要的那样使用路径获取整个 url,可以使用:

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

I know this is a bit late, but I made a clean little function with a little ES6 syntax我知道这有点晚了,但我用一点 ES6 语法做了一个干净的小函数

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

It could also be writen in ES5 like它也可以用 ES5 编写,如

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

Of course IE doesn't support Object.assign , but in my line of work, that doesn't matter.当然 IE 不支持Object.assign ,但在我的工作中,这无关紧要。

Regex provides much more flexibility.正则表达式提供了更多的灵活性。

    //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

My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:我的解决方案适用于包括 Microsoft 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;
    }
}

Let's suppose you have this url path:假设你有这个 url 路径:

http://localhost:4200/landing?query=1#2 http://localhost:4200/landing?query=1#2

So, you can serve yourself by the location values , as follow:因此,您可以通过location values为自己服务,如下所示:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

Now we can conclude you're looking for:现在我们可以得出您正在寻找的结论:

window.location.hostname

You can split the URL string using "/"您可以使用“/”拆分 URL 字符串

Https://exampleurl.com/page1/etc/etc https://exampleurl.com/page1/etc/etc

Const URLsplit = exampleURL.split("/") const URLsplit = exampleURL.split("/")

Result.结果。 Https:, , exampleurl.com, page1, etc , etc, https:, , exampleurl.com, page1, etc , etc,

Var NewURL = URLsplit[2] var NewURL = URLsplit[2]

Result.结果。 exampleurl.com exampleurl.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM