Creating URLSearchParams Objects
You'll learn: Three different ways to create a URLSearchParams object to work with query string data.
The Core Idea
A URLSearchParams object can be instantiated in multiple ways depending on where your query string data comes from. You can create it from a plain string, from a JavaScript object, or directly from an existing URL's query portion. Each approach suits different scenarios in your code.
From a Query String
Pass a string directly, starting with ? or without it:
// With or without the leading '?'
const params1 = new URLSearchParams('?name=Alice&age=30');
const params2 = new URLSearchParams('name=Alice&age=30');
console.log(params1.get('name')); // "Alice"
console.log(params2.get('age')); // "30"
From a JavaScript Object
Pass a plain object with key-value pairs:
const queryData = {
name: 'Bob',
age: 25,
city: 'New York'
};
const params = new URLSearchParams(queryData);
console.log(params.toString()); // "name=Bob&age=25&city=New+York"
From an Existing URL
Extract the search property from a URL object:
const myUrl = new URL('https://example.com/page?color=blue&size=large');
const params = new URLSearchParams(myUrl.search);
console.log(params.get('color')); // "blue"
console.log(params.get('size')); // "large"
Think of It Like This
Imagine preparing ingredients for cooking. You might start with a recipe card (string), gather items from your pantry (object), or take ingredients from someone else's prepared dish (existing URL). Same result, different starting points.
Key Takeaway: You can create URLSearchParams from a query string, a JavaScript object, or by extracting search from a URL object—choose the method that matches your data source.