How can I get the current URL in JavaScript?
Davide S
davide s profile pic

In JavaScript, you can retrieve the current URL (Uniform Resource Locator) of the web page using thewindow.location object. This object provides several properties that contain information about the current URL. Here's a step-by-step guide on how to get the current URL: 1. Access thewindow.location object: Thewindow.location object represents the current URL of the web page. It provides properties likehref,protocol,host,pathname,search, and more. Here's an example:

1
2
3

   var currentURL = window.location;
   

This assigns thewindow.location object to thecurrentURL variable. 2. Retrieve the desired property: Depending on the specific part of the URL you want to extract, you can access the corresponding property of thewindow.location object. Here are some common properties: -href: Returns the complete URL of the current page, including the protocol, host, pathname, and search parameters. -protocol: Returns the protocol (e.g., "http:", "https:", "file:", etc.) of the current page. -host: Returns the hostname and port number of the current page. -pathname: Returns the path and filename of the current page. -search: Returns the query string parameters (if any) of the current page. Here's an example that retrieves the complete URL using thehref property:

1
2
3
4

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

This logs the complete URL of the current page to the console. 3. Accessing additional properties: Apart from the main properties mentioned above, thewindow.location object provides other properties likehostname,port,hash, and more, which you can explore based on your specific needs.

1
2
3
4
5
6
7
8
9

   var hostname = window.location.hostname;
   var port = window.location.port;
   var hash = window.location.hash;

   console.log(hostname);
   console.log(port);
   console.log(hash);
   

This code snippet demonstrates accessing thehostname,port, andhash properties of thewindow.location object. By following these steps, you can retrieve various parts of the current URL using thewindow.location object in JavaScript. Choose the specific property that suits your needs and use it accordingly in your code.