How do I get the current URL in JavaScript?
Rashid D
rashid d profile pic

In JavaScript, you can obtain the current URL using thewindow.location object. Thewindow.location object provides information about the current URL of the document. Here are a few ways to retrieve the current URL: 1. Usingwindow.location.href: - Thewindow.location.href property returns the complete URL of the current page, including the protocol, domain, path, and query parameters.

1
2
3

   const currentURL = window.location.href;
   

ThecurrentURL variable will contain the complete URL, such as"https://www.example.com/path?param=value". 2. Usingwindow.location.toString(): - Thewindow.location.toString() method returns the complete URL of the current page as a string.

1
2
3

   const currentURL = window.location.toString();
   

This will have the same effect as usingwindow.location.href. 3. Usingwindow.location.protocol,window.location.host,window.location.pathname, andwindow.location.search: - You can also access individual components of the URL using properties of thewindow.location object: -window.location.protocol: returns the protocol of the current page (e.g.,"https:"). -window.location.host: returns the hostname and port number of the current page (e.g.,"www.example.com"). -window.location.pathname: returns the path of the current page (e.g.,"/path"). -window.location.search: returns the query parameters of the current page (e.g.,"?param=value").

1
2
3
4
5
6
7

   const protocol = window.location.protocol;
   const host = window.location.host;
   const path = window.location.pathname;
   const query = window.location.search;
   const currentURL = `${protocol}//${host}${path}${query}`;
   

In this example, the variablesprotocol,host,path, andquery store the respective components of the URL, andcurrentURL is constructed by concatenating them together. Choose the method that best suits your requirements. The first two approaches (window.location.href andwindow.location.toString()) provide the complete URL as a single value, while the third approach allows you to access and manipulate individual components of the URL if needed.