gpt4 book ai didi

javascript - 获取不带扩展名的根域名 - Javascript

转载 作者:行者123 更新时间:2023-11-28 05:07:44 26 4
gpt4 key购买 nike

如何在 JavaScript 中从给定 URL 获取不带扩展名的根域名?

示例:

rootDomain("https://www.etsy.com/market/tumblr_clothing") -> etsy

rootDomain("https://petitions.whitehouse.gov/") -> whitehouse

rootDomain("facebook.com") -> facebook

rootDomain("google.ca") -> google

我找到了一个不完整的解决方案:How to get domain name only using javascript?Extract hostname name from string

主要问题是我在创建没有扩展名或子域的解决方案时遇到问题。

解决这个问题的最佳方法是什么?

最佳答案

尝试:

function extractHostname(url) {
var hostname;
if (url.indexOf("//") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
hostname = hostname.split(':')[0];
hostname = hostname.split('?')[0];
return hostname;
}

function extractRootDomainNoExt(url) {
var domain = extractHostname(url),
splitArr = domain.split('.'),
arrLen = splitArr.length;

if (arrLen == 2) {
domain = splitArr[0]
}
else if (arrLen > 2) {
domain = splitArr[arrLen - 2];
//check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
if (splitArr[arrLen - 2].length == 2 && splitArr[arrLen - 1].length == 2) {
domain = splitArr[arrLen - 3];
}
}
return domain;
}

//test extractRootDomainNoExt
console.log("== Testing extractRootDomainNoExt: ==");
console.log(extractRootDomainNoExt("https://www.etsy.com/market/tumblr_clothing"));
console.log(extractRootDomainNoExt("https://petitions.whitehouse.gov/"));
console.log(extractRootDomainNoExt("facebook.com"));
console.log(extractRootDomainNoExt("google.ca"));
console.log(extractRootDomainNoExt("http://www.blog.classroom.me.uk/index.php"));
console.log(extractRootDomainNoExt("http://www.youtube.com/watch?v=ClkQA2Lb_iE"));
console.log(extractRootDomainNoExt("https://www.youtube.com/watch?v=ClkQA2Lb_iE"));
console.log(extractRootDomainNoExt("www.youtube.com/watch?v=ClkQA2Lb_iE"));
console.log(extractRootDomainNoExt("ftps://ftp.websitename.com/dir/file.txt"));
console.log(extractRootDomainNoExt("doesnothaveext/dir/file.txt"));
console.log(extractRootDomainNoExt("websitename.com:1234/dir/file.txt"));
console.log(extractRootDomainNoExt("ftps://websitename.com:1234/dir/file.txt"));
console.log(extractRootDomainNoExt("example.com?param=value"));
console.log(extractRootDomainNoExt("https://facebook.github.io/jest/"));
console.log(extractRootDomainNoExt("//youtube.com/watch?v=ClkQA2Lb_iE"));

*点击“运行代码片段”即可在各种用例中查看这项工作。

这也适用于提取子域和国家/地区编码的域名,例如 classroom.co.uk -> classroom

另请参阅:Extract hostname name from string

关于javascript - 获取不带扩展名的根域名 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com