Here’s a detailed guide to getting the current URL and its components in JavaScript, with examples for common use cases:
1. Get the Full URL
The simplest way to retrieve the entire URL of the current page:
const fullUrl = window.location.href;
console.log(fullUrl); // "https://www.example.com:8080/path/page.html?query=abc#section1"
2. Break Down URL Components
The window.location
object provides access to specific parts of the URL:
Property | Description | Example Output |
---|---|---|
protocol | URL protocol (e.g., http: , https: ) | "https:" |
host | Hostname + port (if specified) | "www.example.com:8080" |
hostname | Domain name (without port) | "www.example.com" |
port | Port number (empty if default) | "8080" |
pathname | Path after the domain | "/path/page.html" |
search | Query string (including ? ) | "?query=abc" |
hash | Fragment identifier (including # ) | "#section1" |
origin | Protocol + hostname + port (read-only) | "https://www.example.com:8080" |
Example:
console.log(window.location.protocol); // "https:"
console.log(window.location.hostname); // "www.example.com"
console.log(window.location.pathname); // "/path/page.html"
console.log(window.location.search); // "?query=abc"
console.log(window.location.hash); // "#section1"
3. Get Query Parameters
Use URLSearchParams
to parse the query string (e.g., ?query=abc&lang=en
):
// Extract all parameters as key-value pairs
const params = new URLSearchParams(window.location.search);
// Get a specific parameter
const query = params.get('query'); // "abc"
const lang = params.get('lang'); // "en"
// Check if a parameter exists
if (params.has('query')) {
console.log('Query exists');
}
// Convert to an object
const paramsObject = Object.fromEntries(params.entries());
console.log(paramsObject); // { query: "abc", lang: "en" }
4. Get the URL of the Referring Page
Use document.referrer
to get the URL of the page that linked to the current page:
const referrer = document.referrer;
console.log(referrer); // "https://www.google.com" (if navigated from Google)
5. Practical Examples
Example 1: Redirect to a New Path
// Redirect to "/new-page" on the same domain
window.location.pathname = '/new-page';
Example 2: Check for a Hash Fragment
if (window.location.hash === '#success') {
alert('Form submitted successfully!');
}
Example 3: Extract and Log All URL Components
const urlComponents = {
FullURL: window.location.href,
Protocol: window.location.protocol,
Host: window.location.host,
Path: window.location.pathname,
QueryParams: Object.fromEntries(new URLSearchParams(window.location.search)),
Hash: window.location.hash
};
console.log(urlComponents);
Example 4: Update Query Parameters
// Add or modify a query parameter
const params = new URLSearchParams(window.location.search);
params.set('page', '2'); // Set ?page=2
// Update the URL without reloading the page
window.history.replaceState({}, '', `${window.location.pathname}?${params}`);
6. Notes
- Browser Only: These methods work in browsers, not in Node.js.
- Dynamic Updates:
window.location
updates automatically when the URL changes (e.g., viapushState
or manual navigation). - Security: Accessing certain parts (e.g.,
origin
) is restricted by the same-origin policy for cross-origin iframes.
Summary Table
Method/Property | Use Case |
---|---|
window.location.href | Get the full URL |
window.location.pathname | Get the path after the domain |
URLSearchParams | Parse and manipulate query strings |
document.referrer | Get the referring page URL |
window.history.pushState() | Modify the URL without reloading the page |
By combining these tools, you can easily read, parse, and manipulate URLs in JavaScript!