Browser APIs & Web APIs
URL & URLSearchParams
Master parsing and building URLs in JavaScript. Learn the URL and URLSearchParams APIs to handle query parameters and parse paths.
1. Introduction
Managing URLs by concatenating strings is error-prone. Modern browsers provide the URL and URLSearchParams APIs to parse, modify, and build URL strings and query parameters safely.
2. Why It Matters
URLs contain characters (like spaces, ampersands, or question marks) that must be escaped. Manually escaping these characters using regex is difficult and can cause bugs. The URL APIs handle character encoding automatically.
3. Real-World Analogy
Think of a Postal Sorting Machine:
- Manual String Editing (Handwritten labels): Writing an address on an envelope: "http://site.com/search?query=tags & comments". If you forget to escape the spaces and ampersands, the mail carrier cannot parse the address, and delivery fails.
- URL API (Postal Envelope Form): An envelope form with separated fields: Country, Zip Code, and Contents. You write values into the fields, and the machine combines and encodes them into a single barcode address that is guaranteed to be parsed correctly.
4. The URL API
The URL constructor parses a URL string, exposing properties to read or modify different parts of the URL:
5. URLSearchParams
The URLSearchParams API provides methods to manage the query string parameters of a URL, handling URL encoding and decoding automatically:
6. Practical Example
This script demonstrates building a secure query URL dynamically with auto-encoded parameters:
7. Common Mistakes
- Passing relative paths without a base URL: Calling
new URL('/pathname')throws a TypeError because the URL constructor requires an absolute path. To parse a relative path, pass the base URL as the second argument:new URL('/pathname', 'https://base.com').
8. Quick Quiz
Q1: What happens to special characters like ampersands or spaces when you set them as query parameters using URLSearchParams?
A) They are ignored
B) They are URL-encoded automatically
Answer: B — URLSearchParams automatically URL-encodes special characters (like converting spaces to + or %20, and & to %26).
9. Scenario-Based Challenge
The Search Filter Coordinator:
You want to read the active query parameters from the browser window URL: window.location.href. If a user filters by tag: tags=active, update the query parameter in the URL string, maintaining other existing query parameters. Write the state manager helper.
10. Debugging Exercise
Explain why this relative path lookup crashes, and how to fix it:
// Objective: parse query params from window pathname path
const relativePath = '/search?q=js&category=code';
const parsedUrl = new URL(relativePath); // crashes with TypeError! Why?
View Solution
Diagnosis: The URL constructor requires an absolute URL with a protocol. Passing a relative path throws a TypeError: Failed to construct 'URL': Invalid URL.
Fix: Pass a dummy base URL as the second argument to parse relative paths successfully, or use URLSearchParams directly if you only need to parse the query string:
const parsedUrl = new URL(relativePath, 'http://dummy.com'); // Works!
console.log(parsedUrl.searchParams.get('q')); // "js"
11. Interview Questions
🟢 Q1: Compare manually building query strings using template literals with using URLSearchParams.
Answer:
• Manual String Building: Requires manual URL encoding (e.g. calling encodeURIComponent()) for every key and value. It is easy to make mistakes with delimiters (like ?, &, or =).
• URLSearchParams: Handles delimiter syntax and URL encoding automatically. It also provides helper methods (like get(), set(), has(), and delete()) to read and modify parameters easily.
12. Production Considerations
- • Browser Support: The
URLandURLSearchParamsAPIs are supported in all modern browsers and Node.js environments. Use them instead of third-party query string parsing libraries to reduce bundle size.