Search code examples
javascriptjquerydnssubdomain

Get the domain name of the subdomain Javascript


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


Solution

  • 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('.');