0

Do you know of a way to get the secondlevel domain of a website via javascript similar to document.location.hostname?

I want to create a mailto bookmarklet that generates an email address from the string "info@" and the secondlevel domain. the issue with document.location.hostname is the "www." prefix.

ilzel
  • 3
  • 2

2 Answers2

16

Negative number can slice from the end, what gives the second level domain:

var domain=location.hostname.split('.').slice(-2).join('.');
brablc
  • 1,621
  • 18
  • 17
  • Wrong for domains like "www.***.co.uk" – Andrey Sep 20 '15 at 13:37
  • 1
    @AndreyP .co.uk is second level domain https://en.m.wikipedia.org/wiki/.co_(second-level_domain) – brablc Sep 20 '15 at 13:40
  • Interesting. Then the original question seems to be mistaken according to its desired behavior. ilzel probably wanted to sent email to info@***.co.uk, not to info@co.uk – Andrey Sep 20 '15 at 13:47
  • @AndreyP the accepted answer is better for the OP. This answer is better for those looking for 2nd level domain and ignoring .co.uk and similar. Thanks for pointing this out. – brablc Sep 20 '15 at 15:40
  • Note that if the goal is to get the SDL and TLD with the intention to set a cookie or send mail, neither solution would always work because of these addresses. I don't think there is a way to determine just from parsing hostname what the correct, "highest-level but not too high" domain would be. – Dtipson Nov 30 '16 at 04:20
1

Quick and dirty...

var domain = location.hostname.split('.').slice(1).join('.');

But that's only going to strip off the first part. If you've got more than one level of server name, that's not going to work. By you should be able to figure it out.

tkone
  • 22,092
  • 5
  • 54
  • 78
  • thanks! just tested t and it works great. in case of subdomains I will correct it manually (before opening the mail client i have to confirm a prompt – ilzel Apr 12 '12 at 23:03