如何从javascript中的url获取顶级域名(基本域名)

问题描述:

我想从JavaScript中的url中提取顶级域名(基本域名)。
例如下面列出的网址列表,我需要得到 google.com (或 google.co.in )视情况而定) 。

I would like to extract the top level domain (base domain) from the url in javascript. For example for the list of urls listed below I need to get google.com (or google.co.in as the case may be) as the result.

www.google.com

www.google.co.in

www.images.google.com

www.images.google.co.in

google.com

google.co.in

images.google.com

images.google.co.in

www.google.com
www.google.co.in
www.images.google.com
www.images.google.co.in
google.com
google.co.in
images.google.com
images.google.co.in

任何人都有一些如何做的想法。没有直接的方法可以在javascript中找到基本的url,我猜想。

Any one got some idea on how to do it. There is no direct method to find the base url in javascript i guess.

谢谢,
Anish

Thanks, Anish

只有在您要获取TLD的网址时,这个工作才有效。

This one works only if you are at the url you want to get the TLD.

function get_top_domain(){
  var i,h,
    weird_cookie='weird_get_top_level_domain=cookie',
    hostname = document.location.hostname.split('.');
  for(i=hostname.length-1; i>=0; i--) {
    h = hostname.slice(i).join('.');
    document.cookie = weird_cookie + ';domain=.' + h + ';';
    if(document.cookie.indexOf(weird_cookie)>-1){
      document.cookie = weird_cookie.split('=')[0] + '=;domain=.' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
      return h;
    }
  }
}