Encoding Query String Values the Right Way
Why a value with & and = breaks a URL, encodeURIComponent vs encodeURI, and URLSearchParams.
By the TurantTools Dev team · Updated October 27, 2026 · 3 min read
Building a URL by gluing strings together breaks as soon as a value contains &, =, # or %. Each value must be encoded on its own before it goes into the query string.
| Method | Result |
|---|---|
| encodeURIComponent on the value | ?q=Tom%20%26%20Jerry%20%3D%20100%25%20fun |
| encodeURI on the whole URL | https://example.com/search?q=Tom%20&%20Jerry%20=%20100%25%20fun |
With the whole-URL method, the & and = in the value stay as they are, so the server sees a second parameter. Encoding the value alone keeps it as one.
The safe way
const url = new URL("https://example.com/search");
url.searchParams.set("q", "Tom & Jerry = 100% fun");
url.toString();URLSearchParamsencodes for you and writes spaces as+, which servers read back as spaces.- Never decode a URL twice:
%2525becomes%25then%.