从任何网址中提取域名后缀

时间:2012-05-16 08:48:23

标签: javascript

我有一个字符串格式的网址:

str="http://code.google.com"

and some other like str="http://sub.google.co.in"      

我想从第一个提取google.com,从第二个字符串提取google.co.in。

我所做的是:

var a, d, i, ind, j, till, total;

a = document.createElement('a');

a.href = "http://www.wv.sdf.sdf.sd.ds..google.co.in";

d = "";

if (a.host.substr(0, 4) === "www.") {
  d = a.host.replace("www.", "");
} else {
  d = a.host;
}

till = d.indexOf(".com");

total = 0;

for (i in d) {
  if (i === till) {
    break;
  }
  if (d[i] === ".") {
    total++;
  }
}

j = 1;

while (j < total) {
  ind = d.indexOf(".");
  d = d.substr(ind + 1, d.length);
  j++;
}

alert(d);

我的代码有效,但它仅适用于“.com”,它不适用于其他像“.co.in”,“co.uk”,直到我手动指定它们,有谁可以告诉我这个解决方案?我不介意,即使我需要更改完整的代码,但它应该工作。谢谢

2 个答案:

答案 0 :(得分:2)

目前唯一的实用解决方案(甚至不能100%运行)是在代码中引用Public Suffix List,并根据需要与该列表同步。

no 算法可以查看域名并找出哪个部分是“注册域名”,哪些部分是子域名。它甚至无法通过询问DNS本身来完成。

答案 1 :(得分:0)

正则表达式对于此类问题非常有用。

https://regex101.com/r/rW4rD8/1

以下代码应符合此目的。

var getSuffixOnly = function (url) {

    var normalized = url.toLowerCase();
    var noProtocol = normalized.replace(/.*?:\/\//g, "");
    var splittedURL = noProtocol.split(/\/|\?+/g);

    if (splittedURL.length > 1){
        noProtocol = splittedURL[0].toString().replace(/[&\/\\#,+()$~%'":*?<>{}£€^ ]/g, '');
    }

    var regex = /([^.]{2,}|[^.]{2,3}\.[^.]{2})$/g;
    var host = noProtocol.match(regex);


    return host.toString();

};

getSuffixOnly(window.location.host);
相关问题