简体   繁体   中英

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.

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.

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'

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"

使用document.location对象及其hosthostname属性。

alert(document.location.hostname); // alerts "stackoverflow.com"

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");
}

Try

document.location.host

or

document.location.hostname

use

window.location.origin

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

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

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.

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.

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;

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.

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

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;
    }
}

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

You can split the URL string using "/"

Https://exampleurl.com/page1/etc/etc

Const URLsplit = exampleURL.split("/")

Result. Https:, , exampleurl.com, page1, etc , etc,

Var NewURL = URLsplit[2]

Result. exampleurl.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM