Course contentsShow
← Web Development
Lesson 958 of 2,98217. URL and History ManagementFree lesson

URL Encoding and Special Characters

How URLSearchParams automatically handles encoding and decoding of special characters.

URL Encoding and Special Characters

You'll learn how URLSearchParams automatically handles the tricky business of encoding and decoding special characters in URLs, so you don't have to worry about it.

The Problem with Special Characters

URLs can only contain certain "safe" characters. Spaces, ampersands, equal signs, and many other characters have special meaning or simply aren't allowed in URLs. For example, a space needs to become %20 or +, and an ampersand (&) becomes %26.

Without proper encoding, a search query like "cats & dogs" would break your URL because the & looks like it's separating two different parameters.

URLSearchParams Does the Heavy Lifting

The beauty of URLSearchParams is that it automatically encodes special characters when you add them, and automatically decodes them when you read them back. You work with normal, readable strings, and it handles the URL-safe formatting behind the scenes.

const params = new URLSearchParams();
params.set('query', 'cats & dogs');
params.set('email', 'user@example.com');

console.log(params.toString());
// "query=cats+%26+dogs&email=user%40example.com"

console.log(params.get('query'));
// "cats & dogs" (decoded automatically!)

Think of It Like a Translator

URLSearchParams acts like a translator between human-readable text and URL-safe format. When you set() a value, it translates to URL language. When you get() a value, it translates back to normal text. You never have to see or manipulate the encoded versions directly.

This is much safer than manually encoding with encodeURIComponent() and forgetting to decode later, or worse, double-encoding by accident.

Key Takeaway: URLSearchParams automatically encodes special characters when building query strings and decodes them when reading values, letting you work with normal strings without worrying about URL formatting rules.