例如,我想从这些主机名中仅提取“google”。
我不想检索主机名,只需要域名而无需顶级域名和子域(如果有的话)。 等等。
我不想检索主机名,只需要域名而无需顶级域名和子域(如果有的话)。 等等。
使用location.host
并从中提取所需部分即可简单实现。以下是一个实用函数:
function extractDomainName(hostname) {
var host = hostname;
host = host.replace(/^www\./i, "");
host = host.replace(/(\.[a-z]{2,3})*\.[a-z]{2,3}$/i, "");
return host;
}
使用.replace()
方法和regex
从完整的hostname
中提取域名并返回。
您可以在此处查看其工作原理。
演示:
function extractDomainName(hostname) {
var host = hostname;
host = host.replace(/^www\./i, "");
host = host.replace(/(\.[a-z]{2,3})*\.[a-z]{2,3}$/i, "");
return host;
}
var tests = ["www.google.com", "www.tutorialspoint.com", "somesite.gov.fr", "www.path.co.ltd"];
tests.forEach(function(hostname) {
console.log(hostname);
console.log(extractDomainName(hostname));
});
正则表达式
和 string.replace()
来实现它,请看我的编辑。 - cнŝdkextractDomainName("secure.payments.google.co.uk")
。 - dandavissecure.payments.google
。 :) - cнŝdk使用位置对象的主机名,您可以在顶级域名之前检查域名。这也会忽略子域名。
var domain = window.location.hostname.match(/([a-z0-9-]*?)\.[a-z]{2,}$/)[1];
console.log(domain);
location.host
- dandavis