Encoding a query parameter, step by step
Say you need to search for "café & bar" via a query parameter. Encoding it correctly means percent-escaping every character outside the unreserved set:
Input: café & bar
Encoded: caf%C3%A9%20%26%20bar
Breaking that down: é becomes %C3%A9 (its UTF-8 bytes, each percent-encoded), the space becomes %20, and & — a reserved character with special meaning in query strings — becomes %26 so it's treated as literal data, not a parameter separator.
Building a full query string
Encoding each value individually, then joining with &, is the safe pattern:
?q=caf%C3%A9%20%26%20bar&page=2&sort=relevance
Notice only the values need encoding — the ?, &, and = structural characters stay as-is, since they're doing their actual job as URL syntax here, not appearing as data inside a value.
The one function that matters most: encodeURIComponent
For encoding a single value going into a URL (not a whole URL), encodeURIComponent() is almost always the correct choice — it escapes reserved characters like &, =, and ? that would otherwise corrupt the query string's structure if they appeared unescaped inside a value. Using the more permissive encodeURI() on a single parameter value under-encodes exactly the characters most likely to break things (see the Complete Guide to URL Encoding for the full distinction).
Common mistakes
- Encoding the entire URL, structure included, when only a value needs it. This can double-encode the
?/&/=characters that should remain literal structural syntax. - Forgetting non-ASCII characters need encoding at all. A URL with a raw
éor中might display fine in a browser (which decodes for display) but fail when parsed strictly elsewhere or copy-pasted into a plain-text context. - Manually replacing only spaces and forgetting other reserved characters.
&,=,#, and+all carry structural meaning and need encoding if they appear as literal data within a value.
FAQ
Do I need to encode the entire URL or just the query values?
Just the values — the ?, &, =, and path separators should stay unencoded since they're structural; only encode the data going into each parameter.
Why does a space sometimes become %20 and other times +?%20 is the general percent-encoding for space; + is a legacy convention specific to application/x-www-form-urlencoded data (like typical HTML form submissions) — the two aren't interchangeable outside that specific context.
Is it safe to encode non-English characters in a URL?
Yes, and necessary — non-ASCII characters must be percent-encoded (as their UTF-8 bytes) to be valid in a URL; most tools and browsers handle this automatically when you submit a form, but manual URL construction needs to do it explicitly.
Encode and decode URLs and query parameters instantly with the URL Encoder/Decoder — everything runs in your browser.