Encoding Special Characters and Edge Cases
You'll learn how URLSearchParams automatically handles the tricky business of encoding spaces, special characters, and even arrays so your query strings stay URL-safe.
The Problem with Raw Query Strings
When you manually build query strings, characters like spaces, ampersands (&), equals signs (=), and non-ASCII characters can break your URL. For example, name=John Doe&role=R&D creates ambiguity—is that four parameters or two?
How URLSearchParams Solves This
URLSearchParams automatically applies percent-encoding (also called URL encoding) to all values. Think of it as a translator that converts "dangerous" characters into safe %XX codes that browsers and servers understand.
const params = new URLSearchParams();
params.set('name', 'John Doe'); // Space becomes %20 or +
params.set('role', 'R&D'); // & becomes %26
params.set('emoji', '🎉'); // Encoded to %F0%9F%8E%89
params.set('special', 'a=b&c=d'); // All special chars encoded
console.log(params.toString());
// "name=John+Doe&role=R%26D&emoji=%F0%9F%8E%89&special=a%3Db%26c%3Dd"
Notice spaces become + in query strings (or %20—both are valid), and every special character gets safely encoded.
Edge Case: Array-Like Values
URLSearchParams doesn't natively handle arrays—it treats each append() call independently:
const params = new URLSearchParams();
params.append('color', 'red');
params.append('color', 'blue');
console.log(params.toString());
// "color=red&color=blue"
Multiple entries with the same key become separate query parameters. The server interprets this as an array.
Key Takeaway: URLSearchParams automatically encodes spaces, special characters, and Unicode safely, eliminating manual encoding headaches. For arrays, use repeated append() calls with the same key name.