Handling Multiple Values
You'll learn how to work with URL parameters that contain multiple values, like filter lists or tag collections.
The Multiple Values Problem
Sometimes a single parameter name needs to hold more than one value. Think of a shopping site where you filter by multiple colors: ?color=red&color=blue&color=green. Or a blog that shows posts with several tags: ?tag=javascript&tag=tutorial&tag=beginner.
When you have the same parameter name repeated multiple times in a URL, URLSearchParams handles this gracefully by storing all values for that key.
Reading Multiple Values
You've already learned get() which returns one value. For multiple values, use getAll():
const url = new URL('https://shop.com?color=red&color=blue&color=green');
const params = url.searchParams;
// get() only returns the FIRST value
console.log(params.get('color')); // "red"
// getAll() returns ALL values as an array
console.log(params.getAll('color')); // ["red", "blue", "green"]
Adding Multiple Values
Use append() (not set()) to add values without replacing existing ones:
const params = new URLSearchParams();
params.append('tag', 'javascript');
params.append('tag', 'web');
params.append('tag', 'tutorial');
console.log(params.toString());
// "tag=javascript&tag=web&tag=tutorial"
Think of append() like adding items to a grocery list, while set() replaces the entire list with one item.
Key Takeaway: Use getAll() to retrieve all values for a parameter name, and use append() to add multiple values without overwriting existing ones.