In JavaScript, you can easily retrieve the current URL of a webpage using the window.location
object. Here’s how to do it:
1. Using window.location.href
This property gives you the full URL of the current page.
Example:
// Get the current URL
let currentURL = window.location.href;
console.log(currentURL);
Explanation:
window.location.href
: Returns the entire URL of the current page, including the protocol (e.g.,http
orhttps
), domain, path, and any query parameters.
2. Other Parts of the URL
If you want to get specific parts of the URL (like the hostname, path, or query parameters), you can use other properties of window.location
:
Example:
let currentURL = window.location.href; // Full URL
let protocol = window.location.protocol; // Protocol (e.g., http: or https:)
let hostname = window.location.hostname; // Hostname (e.g., www.example.com)
let pathname = window.location.pathname; // Path (e.g., /page1)
let search = window.location.search; // Query parameters (e.g., ?id=123)
let hash = window.location.hash; // Hash fragment (e.g., #section)
console.log("Current URL: " + currentURL);
console.log("Protocol: " + protocol);
console.log("Hostname: " + hostname);
console.log("Pathname: " + pathname);
console.log("Search Query: " + search);
console.log("Hash: " + hash);
Example Output:
Current URL: https://www.example.com/page1?id=123#section
Protocol: https:
Hostname: www.example.com
Pathname: /page1
Search Query: ?id=123
Hash: #section
Summary
window.location.href
: Returns the full URL of the current page.- You can also use
window.location.protocol
,window.location.hostname
,window.location.pathname
, etc., to get specific parts of the URL.