encodeURI vs encodeURIComponent
encodeURI preserves URL structure characters:
/ : ? & = + # @ ; ,. Use it for encoding complete URLs that need to remain
functional.
encodeURIComponent encodes ALL special characters. Use it for encoding individual query parameters or path segments where the URL structure characters must also be encoded.
When to Encode a Full URL vs a Query Parameter
- Full URL: Use encodeURI when you have a complete URL like
https://example.com/path?query=value - Query parameter value: Use encodeURIComponent for values like
search?q=hello world→search?q=hello%20world - Path segment: Use encodeURIComponent for individual path parts that may contain special characters
- Data in URL: Use encodeURIComponent when embedding JSON or other data in a URL parameter
Common URL Encoding Mistakes
- Using encodeURI for query parameter values (should use encodeURIComponent)
- Double-encoding already encoded strings
- Forgetting to decode server-side before processing
- Not handling encoding errors when user input is malformed
- Assuming all characters need encoding (letters and digits stay unchanged)
Why Some Characters Stay Unchanged
URL encoding only converts characters that have special meaning or cannot be safely
transmitted. Alphanumeric characters (A-Z, a-z, 0-9) and some safe characters like
- _ . ~ remain unchanged because they are already URL-safe.
Characters like spaces become %20 (or + in form data),
non-ASCII characters become percent-encoded sequences like %E2%82%AC for €.