URL encoding (percent-encoding) converts characters into a format that can be safely transmitted in URLs. Every web developer encounters it, yet it remains a common source of bugs. This guide explains the rules, compares JavaScript encoding functions, and covers the pitfalls that trip up even experienced developers.
RFC 3986: The URL Standard
RFC 3986 defines which characters are allowed in URLs without encoding:
- Unreserved characters (never need encoding):
A-Z a-z 0-9 - _ . ~ - Reserved characters (have special meaning):
: / ? # [ ] @ ! $ & ' ( ) * + , ; =
Everything else must be percent-encoded: the character's UTF-8 byte value expressed as %XX hex pairs. For example, a space becomes %20, and the euro sign (€) becomes %E2%82%AC (three UTF-8 bytes).
JavaScript Encoding Functions
| Function | Preserves | Use For |
|---|---|---|
encodeURI() | Reserved chars + unreserved | Encoding a full URL (preserves structure) |
encodeURIComponent() | Only unreserved chars | Encoding a query parameter value |
URLSearchParams | Handles encoding automatically | Building query strings (recommended) |
The most common mistake: using encodeURI() for a query parameter value. It leaves & and = intact, breaking the query string structure if those characters appear in the value.
Space Encoding: + vs %20
This causes endless confusion:
%20— Used in URL paths and fragment identifiers (RFC 3986)+— Used in query strings (application/x-www-form-urlencoded, HTML forms)
Both are correct in their respective contexts. URLSearchParams uses + for spaces; encodeURIComponent() uses %20.
Common Pitfalls
- Double encoding: Encoding an already-encoded string turns
%20into%2520. Decode first, then encode once. - Encoding the entire URL: Never encode the whole URL including scheme and slashes. Only encode dynamic values.
- Missing encoding on user input: Any user-provided value inserted into a URL must be encoded to prevent injection and broken URLs.
- Path vs query encoding:
/is allowed in paths but must be encoded in query values. UseencodeURIComponent()for values.
Encode and decode URLs instantly with the WizlyTools URL Encoder/Decoder.