EN
JavaScript - get protocol with domain name from page URL
3
points
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 than80
forHTTP
or443
forHTTPS
(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).
As we see the console output is:
'http://localhost:3000'