Get root domain from location.host

mrtsherman picture mrtsherman · May 2, 2012 · Viewed 8.9k times · Source

There are a lot of SO questions that seem to address variations of this question. But they tend to be complex regex answers and I am hoping I can find something simpler.

Given location.host values of

foo.mysite.com
app.foo.mysite.com
mysite.com

How can I get the root domain mysite.com?

I could do something like finding the second to last ., but this seems ugly and wouldn't work for any TLD's like .co.uk. If jQuery has an object that contains this information I am happy to use it.

My goal is to create cookies that exist across all subdomains. To do this I need to find .mysite.com. I'd prefer not to hardcode it.

Answer

mrtsherman picture mrtsherman · May 3, 2012

Given the extremely low likelihood that our domain would ever change from anything other than .com, let alone to a SLD, I coded something like this in.

var temp = location.host.split('.').reverse();
var root_domain = '.' + temp[1] + '.' + temp[0];

The overhead and maintenance of maintaining a TLD or SLD list and comparing against it is not worth the trade off for us.