Get the domain name of the subdomain Javascript

Aleksov picture Aleksov · Nov 13, 2012 · Viewed 32.2k times · Source

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 ...?

Answer

Bergi picture Bergi · Nov 13, 2012
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('.');