如何从javascript中的url获取顶级域名(基本域名) [英] How to get top level domain (base domain) from the url in javascript

查看:213
本文介绍了如何从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;
    }
  }
}

这篇关于如何从javascript中的url获取顶级域名(基本域名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆