If you still decided to do it, you need to do following steps:
Reliably extract hostname, like so:
function extractHostName(url) {
return new URL(url).hostname;
}
Have JSON of all possible TLD, so you can detect and eliminate TLD, like so:
function extractDomain(hostname) {
const tld = JSON.parse(tld.json); // should be in a form of array
const re = new RegExp(`(${tld.join('|').replace('.', '\\.')})$`);
return hostname
.replace(re, '')
.replace(/\.$/, '')
.replace(/^(\w+\.)*/, '');
}