I want to get domain name only using javascript. Ex
vn.search.yahoo.com -> yahoo
vn.search.yahoo.com.vn -> yahoo
sub1.sub2.sub3.abcdef.co.uk -> abcdef
Thank you!
Edit: “domain” = domain without extension (ex: .com, .net, .co.uk…) and without sub domain (ex: www, email, cdn, support…)
Use
location.hostand cut off subdomains and the TLD:update: as @demix pointed out, this fails for 2 and 3-letter domains. It also won’t work for domains like
aero,jobsand dozens others.The only way around is to know valid TLDs in advance, so here is a more appropriate function:
I hope I didn’t miss too many corner cases. This should be available in the
locationobject 🙁Test cases: http://jsfiddle.net/hqBKd/4/
A list of TLDs can be found here: http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1