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 = window.location.host;
// Get the path
const path = window.location.pathname;
// Get query parameters
const search = window.location.search;
CopyUsing 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;
CopyUsing 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;
CopyUsing 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();
CopyUsing 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;
CopyUsing 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;
CopyConclusion:
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.