Modern web development often requires accessing and manipulating URLs. Whether you're building dynamic single-page applications, implementing route guards, or parsing query parameters for API calls, understanding how to work with URLs in JavaScript is essential. This guide covers both the legacy window.location approach and the modern URL() API, with practical code examples you can use in your projects today.
Understanding the Modern URL() API
The built-in URL class provides a convenient interface for creating and parsing URLs according to web standards. While strings have always been sufficient for networking methods, the URL() constructor offers powerful parsing capabilities that make URL manipulation more reliable and maintainable. This modern approach, supported by all current browsers, eliminates the fragile string parsing that plagued earlier JavaScript applications.
1// Create URL from absolute string2let url = new URL('https://example.com/path/page');3 4// Create URL with base for relative references5let url2 = new URL('/path/page', 'https://example.com');6 7// Create new URL relative to existing URL8let baseUrl = new URL('https://example.com/dashboard/');9let newUrl = new URL('../profile', baseUrl);10 11// Access URL components12console.log(url.protocol); // "https:"13console.log(url.host); // "example.com"14console.log(url.pathname); // "/path/page"15console.log(url.search); // ""16console.log(url.hash); // ""URL Components Reference
| Component | Description | Example Value |
|---|---|---|
protocol | URL scheme including colon | "https:" |
host | Hostname and port | "example.com:8080" |
hostname | Just the domain name | "example.com" |
port | Port number | "8080" |
pathname | Path and filename | '/path/page' |
search | Query string with leading ? | '?query=value' |
hash | Fragment identifier with leading # | '#section' |
href | Complete URL string | Full URL |
Accessing the Current URL with window.location
For accessing the current page's URL, the window.location object provides all the components you need. This is particularly useful in client-side navigation and when you need information about the user's current page. The window.location properties give you immediate access to each part of the URL without any parsing overhead.
1// For URL: https://example.com/path/page?category=books2 3window.location.protocol // "https:"4window.location.host // "example.com"5window.location.pathname // "/path/page"6window.location.search // "?category=books"7window.location.hash // ""8 9// Get the full current URL10const currentUrl = window.location.href;11 12// Reconstruct full URL from components13const fullUrl = window.location.protocol + "//" + 14 window.location.host + 15 window.location.pathname;Parsing URL Pathnames
When you need to work with individual path segments, splitting the pathname provides granular access for routing and navigation purposes. This technique is essential for building dynamic single-page applications where you need to determine which content to display based on the URL structure. Proper URL parsing is a fundamental skill for professional web developers building modern web applications.
1// Split pathname into segments2const pathArray = window.location.pathname.split('/');3// Example: ['path', 'to', 'page.html']4 5// Access segments by index6const firstSegment = pathArray[1];7const lastSegment = pathArray[pathArray.length - 1];8 9// Get route segments (filtering empty strings)10function getRouteSegments() {11 return pathArray.filter(segment => segment.length > 0);12}13 14// Reconstruct path from segments15const reconstructedPath = pathArray.join('/');Working with Query Parameters
The URLSearchParams API provides a convenient interface for working with query strings, handling encoding and decoding automatically. This is the recommended approach for modern JavaScript applications, as it eliminates the need for manual string parsing and ensures proper URL encoding for all parameter values.
1// Create URL with query parameters2let url = new URL('https://example.com/search');3 4// Set a parameter5url.searchParams.set('query', 'JavaScript tutorial');6 7// Get a parameter8const query = url.searchParams.get('query');9 10// Check if parameter exists11url.searchParams.has('page');12 13// Set/replace a parameter14url.searchParams.set('page', '1');15 16// Add another parameter with same name17url.searchParams.append('tag', 'beginner');18 19// Get all values for a parameter20url.searchParams.getAll('tag');21 22// Delete a parameter23url.searchParams.delete('page');24 25// Get the final URL with encoded parameters26console.log(url.toString());Iterating Over Parameters
let url = new URL('https://example.com/search?q=JavaScript&page=1');
// Iterate over all parameters
for (const [name, value] of url.searchParams) {
console.log(`${name} = ${value}`);
}
// Output:
// q = JavaScript
// page = 1
URL Encoding and Decoding
Proper URL encoding ensures special characters, spaces, and non-ASCII text don't break your URLs. The URL class handles encoding automatically, but understanding the encoding functions helps when working with strings outside the URL API context.
| Function | Purpose | Example Input | Example Output |
|---|---|---|---|
| encodeURI | Encode entire URL | https://example.com/café | https://example.com/caf%C3%A9 |
| encodeURIComponent | Encode URL components | query=value&sort | query%3Dvalue%26sort |
| decodeURI | Decode URL | https://example.com/caf%C3%A9 | https://example.com/café |
| decodeURIComponent | Decode components | query%3Dvalue | query=value |
1// URL object handles encoding automatically2let url = new URL('https://example.com/search');3url.searchParams.set('query', 'C++ programming');4url.searchParams.set('category', 'bücher');5 6console.log(url.toString());7// Output: https://example.com/search?query=C%2B%2B%20programming&category=%C3%BCcher8 9// Manual encoding for individual parameters10const query = 'JavaScript & TypeScript';11const encoded = encodeURIComponent(query);12// "JavaScript%20%26%20TypeScript"Performance Considerations
Understanding performance characteristics helps you make informed choices when working with URLs in performance-critical applications. The modern URL() API is optimized in all current browsers and provides excellent performance for typical use cases.
1// Less efficient - repeated string parsing2function getComponentsInefficient() {3 const protocol = window.location.protocol;4 const host = window.location.host;5 const pathname = window.location.pathname;6 return { protocol, host, pathname };7}8 9// More efficient - parse once, reuse10function parseUrlOnce() {11 const url = new URL(window.location.href);12 return {13 protocol: url.protocol,14 host: url.host,15 pathname: url.pathname,16 searchParams: url.searchParams17 };18}19 20// For Next.js server components, use props instead21async function ServerComponent({ searchParams }) {22 const category = searchParams.category;23}URL API Performance
100%
Modern browser support
Baseline
Feature status
O(1)
Component access after parse
Best Practices
Following these best practices ensures robust, maintainable URL handling in your applications. These principles help you write cleaner code that handles edge cases gracefully and aligns with industry standards for web development.
Use URL() for Parsing
The URL constructor provides reliable parsing and automatic encoding. It's more robust than manual string manipulation and handles edge cases correctly.
Use URLSearchParams
This API handles all encoding/decoding and provides convenient methods for parameter manipulation without worrying about special characters.
Validate URLs
The URL constructor throws TypeError for invalid URLs, which helps catch issues early during development rather than in production.
Cache Parsed URLs
If you need to access multiple components repeatedly, parse once and reuse the URL object to avoid redundant parsing operations.
Common Use Cases
These practical examples demonstrate how to apply URL manipulation in real-world scenarios you'll encounter in your projects. Whether you're building e-commerce platforms or content management systems, these patterns will serve as valuable reference implementations.
1function buildSearchUrl(baseUrl, query, page = 1) {2 const url = new URL(baseUrl);3 url.searchParams.set('q', query);4 url.searchParams.set('page', page.toString());5 return url.toString();6}7 8// Usage9const searchUrl = buildSearchUrl('https://example.com/search', 'tutorials', 3);10// "https://example.com/search?q=tutorials&page=3"1function requireAuth() {2 const url = new URL(window.location.href);3 const isAuthenticated = checkAuth();4 5 if (!isAuthenticated) {6 const loginUrl = new URL('/login', window.location.origin);7 loginUrl.searchParams.set('redirect', url.pathname);8 window.location.href = loginUrl.toString();9 }10}Frequently Asked Questions
Sources
- MDN Web Docs - URL: URL() constructor - The authoritative source for URL() constructor syntax and browser compatibility
- CSS-Tricks - Get URL and URL Parts in JavaScript - Practical examples of window.location properties and URL manipulation
- JavaScript.info - URL objects - In-depth coverage of URLSearchParams, encoding, and best practices