I would like to extract the base domain from the url in javascript. For example for the list of urls listed below I need to get google.com (or googl
You can try this method
var url = 'https://www.petzlover.com/us/search?pet=1&breed=262';
extractHostname(url,true); //petzlover.com
extractHostname(url); //www.petzlover.com
function extractHostname(url,tld) {
let hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("://") > -1) {
hostname = url.split('/')[2];
}else {
hostname = url.split('/')[0];
}
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
hostname = hostname.split('?')[0];
if(tld){
let hostnames = hostname.split('.');
hostname = hostnames[hostnames.length-2] + '.' + hostnames[hostnames.length-1];
}
return hostname;
}
let url = 'https://www.petzlover.com/us/search?pet=1&breed=262';
let longUrl = 'https://www.fr.petzlover.com/us/search?pet=1&breed=262';
let topLevelDomain = extractHostname(url,true); //petzlover.com
let subDomain = extractHostname(url); //www.petzlover.com
let lengthySubDomain = extractHostname(longUrl); //www.fr.petzlover.com
document.getElementById('top-level-domain').innerHTML = topLevelDomain;
document.getElementById('sub-domain').innerHTML = subDomain;
document.getElementById('lengthy-sub-domain').innerHTML = lengthySubDomain;
function extractHostname(url,tld) {
let hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("://") > -1) {
hostname = url.split('/')[2];
}else {
hostname = url.split('/')[0];
}
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
hostname = hostname.split('?')[0];
if(tld){
let hostnames = hostname.split('.');
hostname = hostnames[hostnames.length-2] + '.' + hostnames[hostnames.length-1];
}
return hostname;
}
span{
font-weight:bold;
font-size:16px;
}
Top Level Domain:
Including sub Domain:
Including lengthy sub Domain: