Get the domain name of the subdomain Javascript

2019-01-13 21:36发布

How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com using javascript ...?

3条回答
冷血范
2楼-- · 2019-01-13 21:43

This is faster

const firstDotIndex = subDomain.indexOf('.');
const domain = subDomain.substring(firstDotIndex + 1);
查看更多
对你真心纯属浪费
3楼-- · 2019-01-13 21:53
var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');

To get only the second-level-domain, you might use

var sndleveldomain = parts.slice(-2).join('.');
查看更多
我只想做你的唯一
4楼-- · 2019-01-13 22:00

The generic solution is explained here http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain From above link

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;
})();
查看更多
登录 后发表回答