Thank you for being a valued part of the CNET community. As of December 1, 2020, the forums are in read-only format. In early 2021, CNET Forums will no longer be available. We are grateful for the participation and advice you have provided to one another over the years.

Thanks,

CNET Support

General discussion

Get url with javascript

Jul 20, 2006 8:58AM PDT

I need to obtain the hostname in the address bar.

Here is my code:

function getHost() {
var url = window.location;
var urlparts = url.split('/');
var host = urlparts[0];
alert(host);
}

This code doesn't work when called. Can somebody tell me why?

I call the function with:
getHost();

Thx.

Discussion is locked

- Collapse -
You're missing a few things...
Jul 24, 2006 4:34AM PDT

Ok, first there is a "location.hostname" that will do this for you, you know? Second, the location is an object that you want the href property to get the url out of it but don't forget that the form of a url is as follows:

<protocol>//<host&gtSad:<port>]/<pathname&gtSad<hash>]

So that what you want to do is get the 3rd element for the host name as well as chop off the port if that is possible as some sites will run on a port other than the standard http and https values.

Regards,
JB

- Collapse -
re: Get url with javascript
Jul 25, 2006 12:03AM PDT

var a = document.URL.split("//"); // split at protocol
a = (a[1] ? a[1] : a[0]).split("/");
// use last element of a; split at /
// host is a[0]; path is a[1..(n-1)]; a[n] is page
alert(a.join("\n"));

- Collapse -
window.location is an object ... not a String ...
May 15, 2007 3:29AM PDT

// try this (add http:// if needed)
function getHost() {
var url = window.location.href;
var nohttp = url.split('//')[1];
var hostPort = nohttp.split('/')[0]
alert (hostPort)
}

- Collapse -
Get url with javascript
Apr 8, 2008 9:04PM PDT

var url = window.location;
var urlparts = url.split('/');
var host = urlparts[0];

when we use window.location it's not return string so please use
var url =""+window.location

- Collapse -
Just use a different script
May 26, 2008 4:24PM PDT