How to get a subdomain using window.location?

LB. picture LB. · Jul 29, 2009 · Viewed 28.1k times · Source

If I have a hostname such as: http://sample.example.com and in Javascript I do window.location.hostname, would I get "example.com" or "sample.example.com"?

If not, how would I be able to get sample.example.com?

Answer

nickf picture nickf · Jul 29, 2009

Yes, window.location.hostname will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:

// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];