That is really not a trivial problem as it might seem at first glance.
Luckily there are libs that solves this, tld-extract is a popular choice which uses Mozilla's Public Suffix List (a volunteer based list). The usage is
var parser = require('tld-extract');
console.log( parser("www.google.com") );
console.log( parser("google.co.uk") );
/**
* >> { tld: 'com', domain: 'google.com', sub: 'www' }
* >> { tld: 'co.uk', domain: 'google.co.uk', sub: '' }
*/
To extract the server address part from email address first split by @
character like this
const email = "john@sub.domain.com"
const address = email.split('@').pop()
const domain = parser(address).domain
See more in depth discussion about the problem solution check the README of a similar python library.
tldextract on the other hand knows what all gTLDs and ccTLDs look like
by looking up the currently living ones according to the Public Suffix
List (PSL). So, given a URL, it knows its subdomain from its domain,
and its domain from its country code.
Make sure to learn about the list on Public Suffix List website and understand it is based on volunteer work and might not be exhaustive at all time.
The Public Suffix List is a cross-vendor initiative to provide an
accurate list of domain name suffixes, maintained by the hard work of
Mozilla volunteers and by submissions from registries, to whom we are
very grateful.
Since there was and remains no algorithmic method of finding the
highest level at which a domain may be registered for a particular
top-level domain (the policies differ with each registry), the only
method is to create a list. This is the aim of the Public Suffix List.