Languages
[Edit]
EN

JavaScript - get protocol with domain name from page URL

3 points
Created by:
troya
332

In this article, we would like to show you how to get protocol with domain name from URL in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const protocol = location.protocol;       // https:
const host     = location.host            // dirask.com
const result   = protocol + '//' + host;  // https://dirask.com

console.log(result);

or:

// ONLINE-RUNNER:browser;

const result = location.origin;

console.log(result);  // https://dirask.com

Warning: location.origin returns port at the end when website is run on a different port than 80 for HTTP or 443 for HTTPS (e.g. 3000 on the below example).

 

Practical example on localhost

In this section, we present the result we get when we use the code from the Quick solution section on http://localhost:3000/ with example application (in this case React App).

JavaScript - get protocol with hostname and port from URL
JavaScript - get protocol with hostname and port from URL

As we see the console output is:

'http://localhost:3000'

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join