Course contentsShow
← JavaScript
Lesson 2314 of 2,72347. Networking PrimitivesFree lesson

Modifying Query Parameters with Set and Delete

Learn to add, update, and remove query parameters using set(), append(), and delete() methods on URLSearchParams.

Modifying Query Parameters with Set and Delete

You'll learn how to add, update, and remove query parameters dynamically using URLSearchParams methods.

Now that you can read query parameters, it's time to modify them. The URLSearchParams object provides simple methods to change the search string without manually parsing or rebuilding it.

The set() Method

The set(name, value) method adds a new parameter or replaces an existing one. Unlike append() (which you've seen), set() ensures only one value exists for that key:

const params = new URLSearchParams('lang=en&theme=dark');

params.set('lang', 'fr');  // Updates existing parameter
params.set('user', 'alex'); // Adds new parameter

console.log(params.toString()); 
// "lang=fr&theme=dark&user=alex"

Think of set() like assigning a variable — it overwrites whatever was there before.

The delete() Method

The delete(name) method removes a parameter entirely:

const params = new URLSearchParams('lang=en&theme=dark&debug=true');

params.delete('debug');

console.log(params.toString()); 
// "lang=en&theme=dark"

It's like erasing a line from a list — the parameter disappears completely.

Practical Example

const url = new URL('https://example.com/search?q=cats&page=2');
const params = url.searchParams;

params.set('page', '3');      // Navigate to next page
params.delete('q');           // Clear search query
params.set('filter', 'new');  // Add new filter

console.log(url.href);
// "https://example.com/search?page=3&filter=new"

Notice how the URL object's href automatically reflects changes to searchParams — they're connected!

Key Takeaway: Use set(name, value) to add or update query parameters and delete(name) to remove them, allowing you to dynamically modify URLs without string manipulation.