Created
October 8, 2020 04:18
-
-
Save aaronpeterson/8c481deafa549b3614d3d8c9192e3908 to your computer and use it in GitHub Desktop.
Get domain name without subdomains using JavaScript? -- Simple solution?
This file contains hidden or 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
/** | |
* Was "Get domain name without subdomains using JavaScript?" on StackOverflow | |
* https://stackoverflow.com/questions/9752963/get-domain-name-without-subdomains-using-javascript | |
*/ | |
const tests = { | |
'www.sidanmor.com': 'sidanmor.com', | |
'exemple.com': 'exemple.com', | |
'argos.co.uk': 'argos.co.uk', | |
'www.civilwar.museum': 'civilwar.museum', | |
'www.sub.civilwar.museum': 'civilwar.museum', | |
'www.xxx.sub.civilwar.museum': 'civilwar.museum', | |
'www.exemple.com': 'exemple.com', | |
'main.testsite.com': 'testsite.com', | |
'www.ex-emple.com.ar': 'ex-emple.com.ar', | |
'main.test-site.co.uk': 'test-site.co.uk', | |
'en.tour.mysite.nl': 'mysite.nl', | |
'www.one.lv': 'one.lv', | |
'www.onfdsadfsafde.lv': 'onfdsadfsafde.lv', | |
'aaa.onfdsadfsafde.aa': 'onfdsadfsafde.aa', | |
// angry comments for... | |
'www.d7143.test.me': 'test.me', | |
'main.test-site.fr': 'test-site.fr' | |
}; | |
console.log(Object.keys(tests).reduce((a, k) => { | |
let result = rootDomain(k); | |
a[k] = `${result} ---> ${result === tests[k]}` | |
return a; | |
}, {})) | |
function rootDomain(hostname) { | |
let parts = hostname.split("."); | |
if (parts.length <= 2) | |
return hostname; | |
parts = parts.slice(-3); | |
if (['co','com'].indexOf(parts[1]) > -1) | |
return parts.join('.'); | |
return parts.slice(-2).join('.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment