Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to get the host name from the following URL. I want to do this using Javascript.

http://www.webmail.com/pages/home.aspx

I want to retrieve "http://www.webmail.com" from the above URL.How can I achieve this using JavaScript?

Thanks in advance..

share|improve this question

4 Answers

up vote 29 down vote accepted
var host = window.location.hostname;

or possibly

var host = "http://"+window.location.hostname;

or if you like concatenation

var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
share|improve this answer
Hi..Thanks for the answer..it worked for me.. – karthik k May 18 '11 at 9:25

To get the hostname: location.hostname

But your example is looking for the scheme as well, so location.origin appears to do what you want in Chrome, but gets not mention in the Mozdev docs. You can construct it with

location.protocol + '//' + location.hostname

If you want the port number as well (for when it isn't 80) then:

location.protocol + '//' + location.host
share|improve this answer
Good answer, i remove mine – Ibu May 18 '11 at 8:45
Firefox 4 doesn't seem to have it, though Chrome 12 does. Is it defined in a specification? – Delan Azabani May 18 '11 at 8:46
@Delan — just noticed that and was editing while you commented. – Quentin May 18 '11 at 8:46
Hi..For getting the port, the example worked like a charm..Thanks for that – karthik k May 18 '11 at 9:24

Try this

alert (window.location.hostname)
share|improve this answer

location.protocol + "//" + location.host if you want to include the port, helpful for when you're working on your local computer with a URL like this: localhost:1329/Home/Login

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.