获取子域的JavaScript域名(Get the domain name of the subdo

2019-07-03 19:18发布

我怎样才能获得域名example.com从一组可能的子域sub1.example.com sub2.example.com sub3.example.com使用JavaScript ...?

Answer 1:

var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');

只得到二级域,你可以使用

var sndleveldomain = parts.slice(-2).join('.');


Answer 2:

这是更快

const firstDotIndex = subDomain.indexOf('.');
const domain = subDomain.substring(firstDotIndex + 1);


Answer 3:

通用的解决方案在这里解释http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain从上面的链接

var domain = (function(){
   var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
   while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
      domain = p.slice(-1-(++i)).join('.');
      document.cookie = s+"="+s+";domain="+domain+";";
   }
   document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
   return domain;
})();


文章来源: Get the domain name of the subdomain Javascript