Created
September 11, 2018 13:50
-
-
Save smitroshin/a12b89534e7e4f21b084fb19896b5bad to your computer and use it in GitHub Desktop.
Extract the domain name from url string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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