Mastering URL Encoding and Decoding
January 5, 2025 8 min read
What is URL Encoding?
URL encoding (percent encoding) converts characters into a format that can be transmitted over the Internet. URLs can only contain certain ASCII characters, so other characters must be encoded.
Why URL Encoding is Necessary
- URLs can only use ASCII characters (0-127)
- Some characters have special meaning in URLs (?&=#)
- Spaces and non-ASCII characters must be encoded
Common Encodings
| Character | Encoded | Usage |
|---|---|---|
| Space | %20 or + | Common in queries |
| ! | %21 | Special character |
| # | %23 | Fragment identifier |
| $ | %24 | Dollar sign |
| & | %26 | Parameter separator |
| = | %3D | Key-value separator |
| ? | %3F | Query string start |
| @ | %40 | At symbol |
JavaScript Examples
encodeURI() vs encodeURIComponent()
// encodeURI() - Encode full URL
const url = "https://example.com/search?q=hello world";
encodeURI(url);
// https://example.com/search?q=hello%20world
// encodeURIComponent() - Encode URL parts
const param = "hello world & goodbye";
encodeURIComponent(param);
// hello%20world%20%26%20goodbye
// Use encodeURIComponent() for query parameters!
const query = `?name=${encodeURIComponent("John & Jane")}`;
// ?name=John%20%26%20Jane
Common Pitfalls
1. Double Encoding
// Wrong - double encoded
const encoded = encodeURIComponent(
encodeURIComponent("Hello World")
);
// Result: Hello%2520World (wrong!)
// Correct
const encoded = encodeURIComponent("Hello World");
// Result: Hello%20World
2. Not Encoding Query Parameters
// Wrong
const url = `api?email=john@example.com`;
// Breaks because @ is not encoded
// Correct
const url = `api?email=${encodeURIComponent("john@example.com")}`;
// api?email=john%40example.com
3. Using + for Spaces
While + is accepted in query strings, %20 is the standard:
// Both work, but %20 is preferred
"hello world" → "hello+world" (old style)
"hello world" → "hello%20world" (modern)
Best Practices
- Always encode user input in URLs
- Use
encodeURIComponent()for query parameters - Use
encodeURI()for full URLs - Decode on server-side after receiving
- Test with special characters
Security Considerations
⚠️ Security Risks
- Not encoding can lead to URL injection attacks
- Always validate decoded values server-side
- Be careful with file paths in URLs
- Don't trust client-side encoding alone
Try It Yourself
Practice URL encoding with our free tools: URL Encoder | URL Decoder
Back to Blog