Removing Parameters
You'll learn how to cleanly remove specific query parameters from a URL using the delete() method.
Understanding Parameter Removal
Once you've created a URLSearchParams object, you often need to remove certain parameters entirely—not just change their values. The delete() method is specifically designed for this purpose. It completely removes a parameter and its value from the collection.
How delete() Works
The delete() method takes a single argument: the name of the parameter you want to remove. If that parameter exists (even multiple times), it removes all occurrences.
const params = new URLSearchParams('sort=date&filter=active&page=2');
console.log(params.toString());
// "sort=date&filter=active&page=2"
// Remove the filter parameter completely
params.delete('filter');
console.log(params.toString());
// "sort=date&page=2"
Notice how filter=active disappears entirely from the query string.
Handling Non-Existent Parameters
Calling delete() on a parameter that doesn't exist is completely safe—it simply does nothing:
const params = new URLSearchParams('theme=dark');
params.delete('missing'); // No error thrown
console.log(params.toString());
// "theme=dark" (unchanged)
Practical Use Case
Think of removing parameters like cleaning up your search filters. When a user unchecks a filter option, you want to remove that parameter from the URL entirely, not just set it to empty:
const searchParams = new URLSearchParams(window.location.search);
// User unchecked "in-stock" filter
searchParams.delete('inStock');
// URL updates without that parameter
Key Takeaway: The delete() method removes query parameters completely from a URLSearchParams object, safely handling cases where the parameter doesn't exist.