Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created September 11, 2018 13:50
Show Gist options
  • Save smitroshin/a12b89534e7e4f21b084fb19896b5bad to your computer and use it in GitHub Desktop.
Save smitroshin/a12b89534e7e4f21b084fb19896b5bad to your computer and use it in GitHub Desktop.
Extract the domain name from url string
const extractHostname = (url) => {
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];
return hostname;
}
const extractRootDomain = (url) => {
let domain = extractHostname(url);
const splitArr = domain.split('.');
const arrLen = splitArr.length;
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;
};
// string = "http://www.blog.classroom.me.uk/index.php"
// console.warn(extractHostname(string));
// Output: www.blog.classroom.me.uk
// console.warn(extractRootDomain(string));
// Output: classroom.me.uk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment