window.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 the
window.location object represents the current URL of the web page. It provides properties like
search, and more. Here's an example:
1 2 3
var currentURL = window.location;
This assigns the
window.location object to the
2. Retrieve the desired property:
Depending on the specific part of the URL you want to extract, you can access the corresponding property of the
window.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 the
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, the
window.location object provides other properties like
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 the
hash properties of the
By following these steps, you can retrieve various parts of the current URL using the