How to get the base URL in JavaScript?

Sometimes, we want to get the base URL in JavaScript.

In this article, we’ll look at how to get the base URL in JavaScript.

How to get the base URL in JavaScript?

To get the base URL in JavaScript, we use the window.location.origin and window.location.host properties.

For instance, we write

const baseUrl = window.location.origin;
const host = window.location.host;

to get the base URL with the protocol with window.location.origin.

To just get the host name, we use the window.location.host property.

Conclusio

To get the base URL in JavaScript, we use the window.location.origin and window.location.host properties.