tags:

views:

420

answers:

4

if I have a hostname as:

http://sample.somedomain.com

and in Javascript I do window.location.hostname would I get "somedomain.com" or "sample.somedomain.com" ?

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

+6  A: 

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];
nickf
nickf, thanks! What is /:\/\/([^\/]+)/ ? Regex expression to execute against?
LB
yes: it finds everything from the first :// to the end or the next / ... this will be the subdomains, domain and tld stuff
nickf
+2  A: 

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

http://www.w3schools.com/HTMLDOM/dom_obj_location.asp

Peter Bailey
+2  A: 

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

Al
A: 

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);
Marcin