'get hostname but check if hostname has subdomain [duplicate]

I have to get a hostname without suffix and without subdomain.

exp:

URL: https://my-domain.com
URL2: https://my-domain.store.com

So I need only the my-domain how can I get this ?



Solution 1:[1]

checkout this

const url = new URL('http://example.com/path/index.html?param=value');
console.log(url.hostname) // gives example.com

and if it has a subdomain:

function getDomain(hostname) {
   hostname = hostname.split('.');
   hostname.reverse();
   return `${hostname[1]}.${hostname[0]}`;
}

url = new URL('http://test.example.com/path/index.html?param=value');
getDomain(url.hostname) // gives example.com

url = new URL('http://example.com/path/index.html?param=value');
getDomain(url.hostname) // gives example.com

taken from here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1