Get the current URL with JavaScript?

Get the current URL with JavaScript?

You can use the window.location object in JavaScript to get the current URL of a web page. The location object is a property of the window object and contains information about the current URL.

Here’s an example of how you can use it to get the current URL:

var currentUrl = window.location.href;
console.log(currentUrl);

This will return the entire URL of the current page, including the protocol (e.g. “http” or “https”), the domain, and any query parameters or hash fragment.

location.origin will only give the protocol and the domain.

var originUrl = window.location.origin;
console.log(originUrl);

You can also use location.pathname to get only the path of the current page

var pathUrl = window.location.pathname;
console.log(pathUrl);

You can use location.search to get any query parameters in the current page

var searchUrl = window.location.search;
console.log(searchUrl);

It’s important to note that the location object is a read-only object, meaning you can’t use it to change the current URL of a page. If you need to change the URL, you can use the window.location object’s assign() method to load a new URL or the replace() method to replace the current URL in the browser’s history.

Leave a Reply