URL Encoding: A Complete Guide for Web Developers
Learn everything about URL encoding (percent-encoding), including encodeURI vs encodeURIComponent, and handling special characters.
URL encoding (percent-encoding) converts characters into a format safe for URLs. It replaces unsafe characters with % followed by two hexadecimal digits.
Why URL Encoding is Necessary
URLs can only contain a limited set of ASCII characters. Spaces, non-ASCII characters, and reserved characters must be encoded. Without encoding, URLs with special characters would be ambiguous or invalid.
encodeURI vs encodeURIComponent
- encodeURIComponent: Encodes ALL special characters. Use for individual query parameter values.
- encodeURI: Preserves URL structure characters (: / ? #). Use for complete URLs.
A common mistake is using encodeURI for query values, which fails to encode & and = that have special meaning in query strings.
Common Examples
Space becomes %20 (or + in form data). Forward slash / becomes %2F. Question mark ? becomes %3F. Non-ASCII characters like é become %C3%A9.
Best Practices
Always encode user input before including in URLs. Use encodeURIComponent for query values. Never double-encode values.
