Question

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?

Was it helpful?

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

OTHER TIPS

First of all, it's window.location, not document.location (document.location works in some browsers but it is not standard)

And yes, location.hostname will return the entire domain name, including any subdomains

Read more here

Window Location

It can be done as below:

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;

Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.

How about this snippet. It might help:

var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);

This does the trick for me:

var host = window.location.host
var subdomain = host.split('.’)[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top