-1

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 ?

universe11
  • 703
  • 1
  • 11
  • 35

1 Answers1

0

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

Yarin_007
  • 1,449
  • 1
  • 10
  • 17
  • What's the point of the `reverse()`? – Bergi May 22 '22 at 23:57
  • it's to deal with multiple sub-domains, it always takes the last 2 zones. he could have implemented it differently, with like hostname[hostname.length-1] – Yarin_007 May 23 '22 at 00:04
  • Ah, I see. Yeah, `${hostname.at(-2)}.${hostname.at(-1)}` would've been more clear. However, a more simple (and more correct, since not all hostnames have at least 2 zones) way to achieve that would be `return hostname.split('.').slice(-2).join('.')` – Bergi May 23 '22 at 00:22
  • Definitely agree, there are a couple of similar examples there – Yarin_007 May 23 '22 at 00:55