452

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.

Community
  • 1
  • 1
Dustin Getz
  • 21,282
  • 15
  • 82
  • 131

15 Answers15

960

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Amin Saqi
  • 18,549
  • 7
  • 50
  • 70
  • 1
    I have a web site and 2 applications in IIS. Eg: **sub.domain.com/v1** and **sub.domain.com/v2** and pages like ***sub.domain.com/v1/Default.aspx*** or _sub.domain.com/v2/Products/Default.aspx_ , etc. How I can get value ***/v2***, the root for my application ***sub.domain.com/v2*** ? – Kiquenet Oct 06 '15 at 08:13
  • @Kiquenet use a javascript IDE like WebStorm, you get to see possible options as you write code. – Bhargav Nanekalva Apr 13 '16 at 09:23
  • 3
    `window.location.origin` is undefined in IE9 (according to the link, it's IE11+). [This answer](http://stackoverflow.com/a/1368295/897326) helped. – Victor Zakharov Feb 24 '17 at 19:49
  • 1
    Obviously helpful for almost everyone except it does not answer the question which is how to extract host part out of URL. Funny the correct answer with getRootUrl function has only 17 vs 609 votes. – Miro Dec 12 '17 at 02:26
  • @Miro the question is answered isn't it, the 2nd bullet point answers the question : window.location.hostname : you'll get sub.domain.com – Paul Feb 01 '18 at 17:20
  • @Paul suppose we have URL as string. Not object window with location. – Miro Feb 02 '18 at 02:50
  • window is not defined – Iman Marashi Mar 29 '18 at 10:25
  • 3
    `window.location.pathname` will **NOT** give `/virtualPath`. It will give `/virtualPath/page.htm` – ebyt Sep 21 '18 at 05:00
169

You could concatenate the location protocol and the host:

var root = location.protocol + '//' + location.host;

For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 6
    it seems like you should use "hostname" rather than "host" to achieve the above results. source: http://stackoverflow.com/questions/6725890/window-location-host-vs-window-location-hostname-and-cross-browser-compatibility – user417669 Nov 10 '13 at 23:10
  • You can use location.origin with the same result. – Sérgio Dec 14 '13 at 07:05
  • 2
    The original question did not ask for the protocol portion of the URL. – Simon East Nov 11 '15 at 08:03
  • 1
    The difference between `hostname` and `host` is [shown here](https://stackoverflow.com/a/11379802/1175496); `host` might include the **`port`**, where `hostname` does *not* include the `port`. I think Christian used `location.host` here so the `var root` value will *include* the `port` value (if any). As @Sérgio says, why `var root = location.protocol + '//' + location.host` **is equivalent** to `location.origin`; – Nate Anderson May 26 '22 at 01:48
55

The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.

Take a look at the URL object:

var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol;  // "http:"
url.hostname;  // "aaa.bbb.ccc.com"
url.pathname;  // "/asdf/asdf/sadf.aspx"
url.search;    // "?blah"
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
36

Use document.location object and its host or hostname properties.

alert(document.location.hostname); // alerts "stackoverflow.com"
n1313
  • 20,555
  • 7
  • 31
  • 46
27

There are two ways. The first is a variant of another answer here, but this one accounts for non-default ports:

function getRootUrl() {
  var defaultPorts = {"http:":80,"https:":443};

  return window.location.protocol + "//" + window.location.hostname
   + (((window.location.port)
    && (window.location.port != defaultPorts[window.location.protocol]))
    ? (":"+window.location.port) : "");
}

But I prefer this simpler method (which works with any URI string):

function getRootUrl(url) {
  return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
danorton
  • 11,804
  • 7
  • 44
  • 52
  • 3
    Thank you! I like the 2nd method better too! especially when on server side javascript, no way to get window.location :) – trillions Jul 09 '13 at 20:43
  • One of the two answers here that don't assume you are on the browser side of things... But check the more recent one from Martin Konecny using new URL. – Will59 May 06 '20 at 14:12
12

Let's suppose you have this url path:

http://localhost:4200/landing?query=1#2

So, you can serve yourself by the location values, as follow:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

Now we can conclude you're looking for:

window.location.hostname
Sunil Shakya
  • 8,097
  • 2
  • 17
  • 20
8

Try

document.location.host

or

document.location.hostname
bluish
  • 26,356
  • 27
  • 122
  • 180
Chris Nielsen
  • 14,731
  • 7
  • 48
  • 54
7

use

window.location.origin

and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"

you will get: http://aaa.bbb.ccc.ddd.com/

Idan Wender
  • 977
  • 8
  • 10
  • This is great, but be warned that apparently it doesn't work on IE11 + WIN7 https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4526233/ – Aurelio Mar 15 '18 at 16:50
3

Check this:

alert(window.location.hostname);

this will return host name as www.domain.com

and:

window.location.host

will return domain name with port like www.example.com:80

For complete reference check Mozilla developer site.

kenorb
  • 155,785
  • 88
  • 678
  • 743
code.rider
  • 1,891
  • 18
  • 21
3

There is another hack I use and never saw in any StackOverflow response : using "src" attribute of an image will yield the complete base path of your site. For instance :

var dummy = new Image;
dummy.src = '$';                  // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'

On an URL like http://domain.com/somesite/index.html, root will be set to http://domain.com/somesite/. This also works for localhost or any valid base URL.

Note that this will cause a failed HTTP request on the $ dummy image. You can use an existing image instead to avoid this, with only slight code changes.

Another variant uses a dummy link, with no side effect on HTTP requests :

var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;

I did not test it on every browser, though.

kuroi neko
  • 8,479
  • 1
  • 19
  • 43
3

I know this is a bit late, but I made a clean little function with a little ES6 syntax

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

It could also be writen in ES5 like

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.

gouessej
  • 3,640
  • 3
  • 33
  • 67
Noah Cardoza
  • 158
  • 2
  • 8
2

I would like to specify something. If someone want to get the whole url with path like I need, can use:

var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
mcanvar
  • 465
  • 6
  • 13
  • why going longer way. It can be get with var fullUrl = window.location.origin+ window.location.pathname – Anant Sep 30 '16 at 13:43
  • but sometimes you want to add something like subdomain between the protocol and hostname e.g. multilanguage etc. – mcanvar Oct 01 '16 at 18:42
1

Regex provides much more flexibility.

    //document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
    //1.
     var r = new RegExp(/http:\/\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com

    //2. 
     var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
mvs
  • 111
  • 5
0

My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:

function getHostname(href) {
    if (typeof URL === 'object') {
        // workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
        var dummyNode = document.createElement('a');
        dummyNode.href = href;
        return dummyNode.hostname;
    } else {
        // Martin Konecny's solution
        return new URL(href).hostname;
    }
}
gouessej
  • 3,640
  • 3
  • 33
  • 67
-1

You can split the URL string using /

const exampleURL = "Https://exampleurl.com/page1/etc/etc"
const URLsplit = exampleURL.split("/")
console.log(URLsplit)
console.log(URLsplit[2])

Result. exampleurl.com

Carson
  • 6,105
  • 2
  • 37
  • 45
jcb01
  • 87
  • 1
  • 4