Search code examples
javascriptsubdomainhostname

How to get a subdomain using window.location?


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?


Solution

  • 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];