在 JavaScript 中确定域名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4610412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:15:56  来源:igfitidea点击:

Determine domain name in JavaScript?

javascriptdns

提问by Shafique

What's the difference between using

使用有什么区别

if (document.domain.toLowerCase().indexOf("domainName") != -1)

and

if(window.location.href.match(/:\/\/(.[^/]+)/)[1].toLowerCase().indexOf("domainName") != -1)

and

if(window.location.hostname.toLowerCase().indexOf("domainName") != -1)

I'm just trying to match on a certain domainName and want to use the best approach.

我只是想匹配某个域名并希望使用最佳方法。

回答by Josiah Ruddell

Best and most readable would be:

最好和最易读的是:

if(location.hostname == "mysite.com"){

}


Update:

更新:

Or as Patrick pointed out if you are only looking for part of the domain name I would use match.

或者正如帕特里克指出的那样,如果您只是在寻找我会使用的域名的一部分match

if(location.hostname.match('mysite')){} // will return null if no match is found

回答by Amjad Masad

All of ur solutions aren't efficient! they will basically match everything that contains the domain name.. e.g. lets say the domain is "domain.com"

你所有的解决方案都不是有效的!它们基本上会匹配包含域名的所有内容.. 例如让我们说域是“domain.com”

  • `http://prefixdomain.com`
  • `http://domain.com.jo`
  • sub-domains `http://sub.domain.com`
  • paths: `http://whatever.com/domain.com`
  • `http://prefixdomain.com`
  • `http://domain.com.jo`
  • 子域`http://sub.domain.com`
  • 路径:`http://whatever.com/domain.com`

so best solution would be

所以最好的解决方案是

function isEquals(myhost){
              var hostName = window.location.hostname.split('.');
              myhost = myhost.split(".");
              //handle stuff like site:.com or ..com
              for (var x in myhost)
                if (myhost[x] == "") myhost.splice(x,1);

          //j is where to start comparing in the hostname of the url in question
          var j = hostName.length - myhost.length;
          for(var i in myhost)
          {
              //if j is undefined or doesn't equal the hostname to match return false 
              if (!hostName[j] || hostName[j].toLowerCase() != host[i].toLowerCase())
                  return false;
              j++;
          }
          return true;
      }

回答by Grant Miller

Readable Method:

可读方法:

You can use endsWith()to compare the end of the hostnamestring with the domain name:

您可以使用endsWith()hostname字符串的结尾与域名进行比较:

location.hostname === 'stackexchange.com' || location.hostname.endsWith('.stackexchange.com')

Note:This requires ECMAScript 6 (ES6) support.

注意:这需要 ECMAScript 6 (ES6) 支持。

Short Method:

短法:

Or if you would prefer to use a regex with the test()method, you can use:

或者,如果您更喜欢在该test()方法中使用正则表达式,则可以使用:

/(^|\.)stackexchange\.com$/.test(location.hostname)

Split/Join Array-to-String Method:

拆分/连接数组到字符串方法:

Additionally, you can also split()the hostnameinto an array based on the .character. Then you can take the last two elements (the domain name and extension) using slice(), and join()them back together with the .character as the separator, which will allow you to compare directly to the expected domain name:

此外,您还可以split()hostname到一个数组基础上的.字符。然后,您可以使用 , 取最后两个元素(域名和扩展名)slice(),并将join()它们与.字符一起作为分隔符,这将允许您直接与预期的域名进行比较:

location.hostname.split('.').slice(-2).join('.') === 'stackexchange.com'

This will return true for the following types of URLs:

对于以下类型的 URL,这将返回 true:

回答by user113716

The first and third should be simple and quick. Of the two, I don't think it really matters as long as you're just testing the domain.

第一个和第三个应该简单快捷。在这两者中,只要您只是在测试域,我认为这并不重要

If you're testing a sub-domain, then consider that document.domainbe modified in javascript, while window.location.hostnamecan't.

如果您正在测试子域,请考虑document.domain在 javascript中对其进行修改,而window.location.hostname不能。

回答by jpsimons

Well, window.locationis the more standard way, so I'd suggest that over document.domain. IndexOf will match substrings, which probably isn't what you want. Why not just:

嗯,window.location是更标准的方式,所以我建议结束document.domain. IndexOf 将匹配子字符串,这可能不是您想要的。为什么不只是:

window.location.hostname == "stackoverflow.com"?

I guess for some sites you may have an optional subdomain. Like www.domain.com and just domain.com both going to the same place. If that's a concern you could make some ugly regex, or you could just split on dots:

我想对于某些网站,您可能有一个可选的子域。就像 www.domain.com 和只是 domain.com 都去同一个地方。如果这是一个问题,您可以制作一些丑陋的正则表达式,或者您可以在点上拆分:

var domainParts = window.location.hostname.split(".");
domainParts[domainParts.length - 2] == "stackoverflow"

I don't think case matters, at least in the browsers I tried (Firefox and Chrome) they normalize the domain name to lowercase automatically.

我认为大小写无关紧要,至少在我尝试过的浏览器(Firefox 和 Chrome)中,它们会自动将域名规范化为小写。