Well simply using location.host
and extract the wanted part from it, this is a utility function that you can use:
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;
}
It takes the whole hostname
and returns only the domain name from it using .replace()
method with regex
to extract only the domain name.
You can see it workinh here.
Demo:
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));
});