How to Get the Current URL in JavaScript

Facebook logoTwitter logoLinkedin logo
image with "How to Get the Current URL in JavaScript" text and vectors

In this blog post, we will learn how to get the current URL in JavaScript. Explore different methods to obtain the current page URL using JavaScript.

Using the window.location Object:

JavaScript provides the window.location object, which contains information about the current URL. You can access various properties of this object to obtain specific parts of the URL. Here's how you can use it:

// Get the entire URL
const currentURL = window.location.href;

// Get the protocol (http, https, etc.)
const protocol = window.location.protocol;

// Get the host (domain)
const host =;

// Get the path
const path = window.location.pathname;

// Get query parameters
const search =;

Using document.URL:

You can also retrieve the current URL by accessing the document.URL property, which contains the full URL as a string. Here's an example:

const currentURL = document.URL;

Using window.location.href:

Another way to obtain the full current URL is by using window.location.href, which returns the complete URL as a string:

const currentURL = window.location.href;

Using window.location.toString():

The window.location.toString() method can also be used to get the current URL as a string:

const currentURL = window.location.toString();

Using window.location.origin:

If you're interested in just the origin (protocol, host, and port), you can use window.location.origin:

const origin = window.location.origin;

Using window.location.hash:

To retrieve the URL fragment identifier (the portion of the URL after the "#" symbol), you can use window.location.hash:

const hash = window.location.hash;


Retrieving the current URL in JavaScript is a straightforward task thanks to the various methods provided by the browser's window.location object. Depending on your specific needs, you can access different properties to obtain the complete URL or its individual components. Whether you're building a web application, implementing user tracking, or simply enhancing the user experience, knowing how to get the current URL is a valuable skill for any web developer.