Get root domain from location.host

There are many questions that seem to affect options for this issue. But they are usually complex, regular answers, and I hope I can find something simpler.

Given location.host values

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

How can I get the root domain of mysite.com ?

I could do something like search second to last . but it seems ugly and will not work for any TLD such as .co.uk . If jQuery has an object containing this information, I am glad to use it.

My goal is to create cookies that exist in all subdomains. For this I need to find .mysite.com . I would rather not print it.

+6
source share
3 answers

Given the extremely low probability that our domain will change from anything other than .com, not to mention SLD, I encoded something like this.

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

Overhead and maintaining a TLD or SLD list and comparing it is not a compromise for us.

+7
source

You cannot name .co.uk as TLD. This is actually a second level domain . Therefore, what will be the root domain will always be ambiguous.
However, you can list all available TLD and second level domains and try to find a match. But it will be a very expensive and tedious operation.
If you want to do this, this TLD and SLD List may be useful:

+3
source

if you want it all on one line -

 document.domain.split('.').reverse().splice(0,2).reverse().join('.') 

or

 location.hostname.split('.').reverse().splice(0,2).reverse().join('.') 

for inputs: 'foo.example.com', 'foo.bar.example.com', 'foo.bar.fizz.buzz.example.com'

he will return: 'example.com'

+1
source

Source: https://habr.com/ru/post/914756/


All Articles