Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active November 5, 2020 11:03
Show Gist options
  • Save lewdev/9be8866cd8e9552c0bb015f5fda0a50d to your computer and use it in GitHub Desktop.
Save lewdev/9be8866cd8e9552c0bb015f5fda0a50d to your computer and use it in GitHub Desktop.
extractHostname & extractRootHostname extracts the domain name and the root domain name too for common URLs.
//See also my answer on StackOverflow: https://stackoverflow.com/a/23945027/1675237
const extractHostname = url => {
//find & remove protocol (http, ftp, etc.) and get hostname
let hostname = url.split('/')[url.indexOf("//") > -1 ? 2 : 0];
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
return hostname.split('?')[0];
};
const extractRootHostname = url => {
let domain = extractHostname(url),
splitArr = domain.split('.'),
arrLen = splitArr.length
;
//extracting the root domain here
//if there is a subdomain
if (arrLen > 2) {
domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
//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) {
//this is using a ccTLD
domain = splitArr[arrLen - 3] + '.' + domain;
}
}
return domain;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment