URL Encoding Explained: Percent-Encoding, Query Strings and Common Mistakes
URLs can only contain a limited set of characters. Everything else must be percent-encoded, and getting it wrong breaks links, forms and APIs.
How percent-encoding works
RFC 3986 defines a small set of unreserved characters that never need encoding: A–Z a–z 0–9 - . _ ~. Other characters are converted to UTF-8 bytes and each byte is written as % followed by two hexadecimal digits:
Reserved characters such as / ? # & = : have structural meaning. They must be encoded when they appear inside a value, otherwise they split the URL in the wrong place.
encodeURIComponent vs encodeURI
Use encodeURIComponent for each value you insert into a URL. Use encodeURI only for a complete URL that is already correctly structured.
+ or %20?
In application/x-www-form-urlencoded data (HTML form submissions and many query strings), a space may be written as +. Elsewhere, such as in the path, + is a literal plus sign. Encoding spaces as %20 is always safe.
Build query strings with URLSearchParams
Common mistakes
- Double encoding: encoding an already-encoded value turns
%20into%2520. - Forgetting to encode user input, which breaks links or lets values inject extra parameters.
- Putting secrets in URLs. URLs end up in browser history, server logs and analytics; send sensitive data in the request body instead.