How to extract the hostname portion of a URL in JavaScript

hostname, javascript

Solution

Suppose that you have a page with this address: `http://sub.domain.com/virtualPath/page.htm`.

Use the following in page code to achieve those results:

Property Result

`window.location.host` `sub.domain.com:8080` or `sub.domain.com:80`

`window.location.hostname` `sub.domain.com`

`window.location.protocol` `http:`

`window.location.port` `8080` or `80`

`window.location.pathname` `/virtualPath`

`window.location.origin` `http://sub.domain.com` (Might include `:port` too*****)

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.

Problem

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.

Original source

Related problems