Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a subdomain using window.location?

Tags:

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?

like image 938
LB. Avatar asked Jul 29 '09 15:07

LB.


People also ask

What does Window location Origin return?

Definition and Usage The origin property returns the protocol, hostname and port number of a URL.

How do I get the current domain in HTML?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.

What is true about a subdomain?

To recap, a subdomain is the portion of a URL that comes before the “main” domain name and the domain extension. For example, docs.themeisle.com . Subdomains can help you divide your website into logical parts or create separate sites, for example a separate blog for each sports team.


2 Answers

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]; 
like image 94
nickf Avatar answered Sep 22 '22 04:09

nickf


It can be done as below:

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false; 
like image 22
Ilhami Mounir Aziz Girgis Avatar answered Sep 22 '22 04:09

Ilhami Mounir Aziz Girgis