Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get root domain from location.host

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.

like image 350
mrtsherman Avatar asked May 02 '12 21:05

mrtsherman


1 Answers

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.

like image 91
mrtsherman Avatar answered Sep 28 '22 00:09

mrtsherman