You can use the window.location object in JavaScript to get the current URL. The location object has several properties that can be used to get different parts of the URL.

Here are some examples of how to use the location object to get the current URL:

window.location.href: Returns the entire URL of the current page, including the protocol (http or https), the domain name and the path.

let currentUrl = window.location.href;
console.log(currentUrl); // ""

window.location.origin: Returns the protocol and the domain name of the current page.

let origin = window.location.origin;
console.log(origin); // ""

window.location.pathname: Returns the path of the current page.

let pathname = window.location.pathname;
console.log(pathname); // "/path/to/page"

You can also use the property to get the query parameters of the current page.

let search =;
console.log(search); // "?param1=value1&param2=value2"

It’s worth noting that the location object is a read-only property, you cannot change the URL of the current page using the location object.

You can use any of these methods depending on your requirement.

Also Read:

Categorized in: