URL Encode/Decode
Encode and decode URL components
When URL Encoding Is Required
URLs are restricted to a safe subset of ASCII characters. Spaces, special characters, and non-ASCII characters must be percent-encoded as %XX where XX is the byte value in hexadecimal. The space character becomes %20 (or + in query strings). An ampersand in a query parameter value must be encoded as %26 or it will be interpreted as a parameter separator.
encodeURIComponent vs. encodeURI
JavaScript provides two functions with different scopes:
encodeURIComponent— Encodes everything exceptA-Z a-z 0-9 - _ . ! ~ * ' ( ). Use this for individual query parameter values and path segments.encodeURI— Also preserves: / ? # [ ] @ ! $ & ' ( ) * + , ; =because these have structural meaning in URLs. Use this only for full URLs, never for parameter values.
Common Encoding Mistakes
- Encoding an entire URL with
encodeURIComponentbreaks the slashes and colons, making it unusable as a URL. - Forgetting to encode query parameter values that contain
&,=, or+causes those characters to be misinterpreted by the server. - Double-encoding: passing an already-encoded string through another encode call turns
%20into%2520. Always decode before re-encoding if you are not sure of the input state.
Plus Sign in Query Strings
In application/x-www-form-urlencoded format (HTML form submissions), + represents a space, and %2B represents a literal plus sign. In URL path segments, + is a literal plus, not a space. This mismatch is a common source of decoding bugs in web frameworks.