Search code examples
javascripturlhostname

How to get the full host name in Javascript including HTTP?


I have a problem with getting the host name in Javascript, I have used the code below:

document.location.replace("http://"+ document.location.host + "/another-page")

The code works fine, it gets the host name and replaces the documents URL with the new one.

The problem is with the document.location.host, it only returns the host like this: www.xxx.com without the http part. This is not a scalable way of doing it, cause locally the site runs on http and on the server it runs on https. I don't want to manually change the http part.

So is there a better sollution to automaticly get the full name of a host including http(s)?


Solution

  • is this location.origin what you are looking for?

    or you can get protocol only using this location.protocol

    See more here - https://developer.mozilla.org/en-US/docs/Web/API/Location

    console.log('location.protocol -', location.protocol);
    console.log('location.origin -', location.origin);