Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the hostname portion of a URL in JavaScript

Is there a really easy way to start from a full URL:

document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah" 

And extract just the host part:

aaa.bbb.ccc.com 

There's gotta be a JavaScript function that does this reliably, but I can't find it.

like image 209
Dustin Getz Avatar asked Sep 02 '09 15:09

Dustin Getz


People also ask

How do I find the hostname of a URL?

The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').

How can we get hostname and port information in JavaScript?

If you only want to return the hostname value (excluding the port number), use the window. location. hostname method instead. This will return a string value containing the hostname and, if the port value is non-empty, a : symbol along with the port number of the URL.

What is hostname in JS?

hostname property returns the host (IP adress or domain) of a URL. The location. hostname property can also be set, to navigate to the same URL with a new hostname.

What is location host?

The Location Host property in HTML is used to sets or returns the hostname and port of a URL. The Location Hash property doesn't return the port number if it is not specified in the URL. Syntax: It returns the host property.


1 Answers

suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm. use the following in page code to achive those results:

  • window.location.host : you'll get sub.domain.com:8080 or sub.domain.com:80
  • window.location.hostname : you'll get sub.domain.com
  • window.location.protocol : you'll get http:
  • window.location.port : you'll get 8080 or 80
  • window.location.pathname : you'll get /virtualPath
  • window.location.origin : you'll get http://sub.domain.com *****

Update: about the .origin

***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.

Special thanks to @torazaburo for mentioning that to me.

like image 196
Amin Saqi Avatar answered Oct 04 '22 00:10

Amin Saqi