37

How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com using javascript ...?

Aleksov
  • 1,200
  • 5
  • 17
  • 27
  • 3
    What about `sub1.example.co.uk`? http://publicsuffix.org/ – SLaks Nov 13 '12 at 19:29
  • This is one of the options, thanks for the correction – Aleksov Nov 13 '12 at 19:31
  • Do you want the domain name for sub3.example.com.ua to be example.com or example.com.ua? – Matt Zeunert Nov 13 '12 at 19:34
  • `example.com.ua` I need to allow the use of a script on a specific domain and its subdomains, while prohibiting its use in other domains. So I need to make a selection for the domain name. – Aleksov Nov 13 '12 at 19:39
  • 1
    And what would it be for, for example, [`meta.cooking.stackexchange.com/`](http://cooking.stackexchange.com/) and [`http://cooking.stackexchange.com/`](http://cooking.stackexchange.com/)? – David Thomas Nov 13 '12 at 19:43
  • it will be `stackexchange.com` – Aleksov Nov 13 '12 at 19:45
  • Use location.host and cut off subdomains..check this post http://stackoverflow.com/questions/8253136/how-to-get-domain-name-only-using-javascript – Scorpio Nov 13 '12 at 19:46
  • I'm not great with regex, but I'm thinking you need something like /[a-z]+\.[a-z]{2,6}?\.?[a-z]{2,6}/i –  Nov 13 '12 at 19:48
  • @Llepwryd: No. Regex is not needed, and this one will not do the expected. – Bergi Nov 13 '12 at 19:51
  • Thank you all! The issue is solved! – Aleksov Nov 13 '12 at 19:54

7 Answers7

92
var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');

To get only the second-level-domain, you might use

var parts = location.hostname.split('.');
var sndleveldomain = parts.slice(-2).join('.');
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 5
    @Bergi - I know the OP was meant for domain names and not IP addresses, but I just wanted to point out that while this works great for named addresses, it doesn't work for IP based addresses and incorrectly breaks them up (i.e. 127.0.0.1 returns "0.1"). – johntrepreneur Jun 27 '13 at 18:07
  • @johntrepreneur: You mean when the `hostname` is an IP address? Yeah, but I can't think of a result that would make much sense in that case… should it be returned unmodified? – Bergi Jun 27 '13 at 18:19
  • @Bergi - yeah hostname is IP address as uncommon as that is (except in development). Yea, I just checked that it has 3 dots (4 parts after split) and that the hostname (minus dots) was only digits. `if (arrHostname.length == 4 && /^\d+$/.test(hostname.replace(/\./g, ''))) // is IP address; return hostname unmodified` – johntrepreneur Jun 27 '13 at 18:46
  • @Bergi - sorry to confuse you. This OP is really targeted at domain names and not domain IP's so my comment doesn't really apply. I just had implemented it and noticed it wasn't working in my case using 127.0.0.1 so I thought I'd mention it even though it's not totally relavant to OP. – johntrepreneur Jun 27 '13 at 18:52
  • 2
    @HankYang: `co.uk` is the subdomain (second level domain), my snippet works just as well for that. If you are looking for effective second level domains, you will have to incorporate the [public suffix list](https://publicsuffix.org/) in your application. – Bergi May 23 '15 at 07:58
  • wont this run into issues with TLDs like `co.uk` as @Bergi mentioned?? – oldboy Aug 02 '19 at 01:36
  • @BugWhisperer As mentioned, `co.uk` is not a TLD. – Bergi Aug 02 '19 at 07:52
  • If anything, isn't `co` by itself the SLD, whereas the TLD is `uk`?? – oldboy Aug 02 '19 at 07:58
  • @oldboy See my answer below (https://stackoverflow.com/a/60470476/9638991) and https://publicsuffix.org/ for details about how to fix issues with public suffixes (e.g. `co.uk`) – kimbo Feb 29 '20 at 23:10
7

The accepted answer will work to get the second level domain. However, there is something called "public suffixes" that you may want to take into account. Otherwise, you may get unexpected and erroneous results.

For example, take the domain www.amazon.co.uk. If you just try getting the second level domain, you'll end up with co.uk, which is probably not what you want. That's because co.uk is a "public suffix", which means it's essentially a top level domain. Here's the definition of a public suffix, taken from https://publicsuffix.org:

A "public suffix" is one under which Internet users can (or historically could) directly register names.

If this is a crucial part of your application, I would look into something like psl (https://github.com/lupomontero/psl) for domain parsing. It works in nodejs and the browser, and it's tested on Mozilla's maintained public suffix list.

Here's a quick example from their README:

var psl = require('psl');

// TLD with some 2-level rules.
psl.get('uk.com'); // null);
psl.get('example.uk.com'); // 'example.uk.com');
psl.get('b.example.uk.com'); // 'example.uk.com');
kimbo
  • 2,513
  • 1
  • 15
  • 24
5

This is faster

const firstDotIndex = subDomain.indexOf('.');
const domain = subDomain.substring(firstDotIndex + 1);
faboulaws
  • 1,909
  • 16
  • 16
0

The generic solution is explained here http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain From above link

var domain = (function(){
   var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
   while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
      domain = p.slice(-1-(++i)).join('.');
      document.cookie = s+"="+s+";domain="+domain+";";
   }
   document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
   return domain;
})();
Dipu R
  • 545
  • 1
  • 5
  • 22
0

    function getDomain() {
        const hostnameArray = window.location.hostname.split('.')
        const numberOfSubdomains = hostnameArray.length - 2
        return hostnameArray.length === 2 ? window.location.hostname : hostnameArray.slice(numberOfSubdomains).join('.')
    }
    console.log(getDomain());

This will remove all subdomains, so "a.b.c.d.test.com" will become "test.com"

LWC
  • 1,084
  • 1
  • 10
  • 28
Pietro Coelho
  • 1,894
  • 1
  • 26
  • 34
0

If you want to verify if a specific subdomain exists

var parts = location.hostname.split('.');
if(parts.includes('subdomain_to_search_here')){
   //yes
}else{
   //no
}
Alexandru Burca
  • 427
  • 1
  • 4
  • 15
-1

some more robust version, which is independent of the subdomain count

function getDomain() {
   const hostname = window.location.hostname.split('.');
   hostname.reverse();
   return `${hostname[1]}.${hostname[0]}`;
}
Polliny
  • 89
  • 1
  • 4