我有一个字符串格式的url,如下所示:
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”,直到我手动指定它们,谁能告诉我解决这个问题的方法?我不介意我甚至需要更改完整的代码,但它应该可以工作。谢谢
发布于 2012-05-16 16:50:02
目前唯一实用的解决方案(甚至不是100%有效)是在代码中引用Public Suffix List,并根据需要与该列表同步。
没有一种算法可以查看域名并找出哪个部分是“注册域名”,哪些部分是子域。它甚至不能通过询问DNS本身来完成。
发布于 2016-02-17 23:03:54
正则表达式对于这类问题是非常强大的。
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);https://stackoverflow.com/questions/10615013
复制相似问题