Adding and Modifying Parameters
You'll learn how to programmatically add new query parameters or update existing ones using URLSearchParams methods.
The Core Idea
Once you've created a URLSearchParams object, you can change its contents using two key methods: set() and append(). Both add parameters, but they behave differently when a parameter name already exists.
Using set() to Add or Replace
The set() method adds a new parameter or replaces an existing one with the same name:
const params = new URLSearchParams('color=red&size=large');
// Replace existing parameter
params.set('color', 'blue');
console.log(params.toString()); // "color=blue&size=large"
// Add new parameter
params.set('material', 'cotton');
console.log(params.toString()); // "color=blue&size=large&material=cotton"
Using append() for Multiple Values
The append() method adds a parameter without removing existing ones with the same name. This lets you have multiple values for one key:
const params = new URLSearchParams();
params.append('tag', 'javascript');
params.append('tag', 'webdev');
params.append('tag', 'tutorial');
console.log(params.toString()); // "tag=javascript&tag=webdev&tag=tutorial"
Think of set() like assigning a value to a variable—it overwrites. Think of append() like adding items to an array—it accumulates.
Practical Example
const searchUrl = new URL('https://example.com/search?q=laptop');
const params = searchUrl.searchParams;
params.set('q', 'tablet'); // Update search term
params.append('filter', 'new'); // Add filter
params.append('filter', 'sale'); // Add another filter
console.log(searchUrl.href);
// "https://example.com/search?q=tablet&filter=new&filter=sale"
Key Takeaway: Use set() when you want one value per parameter name, and append() when you need multiple values for the same parameter.