Say that I have a domain subdomain.domain.com
, when I check the document.domain
I'm getting the result subdomain.domain.com
, what can I do to get only the original domain without the sub domain, for example: domain.com
Asked
Active
Viewed 1,133 times
0

udidu
- 8,269
- 6
- 48
- 68
1 Answers
1
This will work for a .com
domain in the example you specified, you would have to adjust the slice for .co.uk
, .com.au
and some other TLDs:
document.domain.split(".").slice(-2).join(".");

Andy E
- 338,112
- 86
- 474
- 445
-
Thanks but I don't know what will be the domain, I need something more generic. – udidu Apr 18 '12 at 13:14
-
@UdiTalias: can you guarantee that it will only be `subdomain.domain.tld` or can it be `subdomain.subdomain.domain.tld`? – Matt Apr 18 '12 at 13:16
-
It can be also subdomain.subdomain.domain.tld. Actually I don't know what will be the domain, it can be anything... – udidu Apr 18 '12 at 13:17
-
@Udi: then you're going to struggle because the only way to do it is to have an up-to-date list of all TLDs (keeping note of which have CCSLDs), and continuing to maintain it as new ones are introduced. – Andy E Apr 18 '12 at 13:29
-
@Udi: see [this related question](http://stackoverflow.com/questions/399250/going-where-php-parse-url-doesnt-parsing-only-the-domain) looking for a similar solution in PHP for more information. – Andy E Apr 18 '12 at 13:34
-
Posting this for [Yanislav Tankov](http://stackoverflow.com/users/6640908/yanislav-tankov): `document.domain.split(".").slice(-2).join(".");` works for me for all domains .com, .co.uk, sub.domain.co.uk domain.co... etc. BUT not for male.domain.co.uk – NathanOliver Jul 26 '16 at 16:45