URL Encoding and Decoding
You'll learn how to safely include special characters in URLs using encodeURIComponent() and decodeURIComponent().
Why URLs Need Encoding
URLs can only contain certain "safe" characters. Special characters like spaces, ampersands (&), question marks (?), or international characters must be converted into a percent-encoded format that browsers can safely transmit.
Think of it like packing fragile items for shipping: you wrap them in protective material (encoding) so they arrive intact, then unwrap them (decoding) when they reach their destination.
Using encodeURIComponent()
This function converts special characters into their URL-safe equivalents:
const search = "cats & dogs";
const encoded = encodeURIComponent(search);
console.log(encoded); // "cats%20%26%20dogs"
const url = `https://api.example.com/search?q=${encoded}`;
// https://api.example.com/search?q=cats%20%26%20dogs
Notice how the space becomes %20 and the ampersand becomes %26. Without encoding, that & would be interpreted as separating URL parameters!
Using decodeURIComponent()
This reverses the process, converting percent-encoded characters back to their original form:
const encoded = "cats%20%26%20dogs";
const decoded = decodeURIComponent(encoded);
console.log(decoded); // "cats & dogs"
Common Use Cases
Always encode user input before adding it to URLs:
const username = "user@example.com";
const profileUrl = `https://site.com/profile?email=${encodeURIComponent(username)}`;
// Correctly encodes the @ symbol
When reading URL parameters, decode them to get the original values back.
Key Takeaway: Use encodeURIComponent() to safely convert special characters before adding them to URLs, and decodeURIComponent() to restore encoded values back to their original form.