URL Encoding Explained: When to Use encodeURIComponent vs encodeURI
2026-06-03 · 5 min read
Picking the wrong URL-encoding function silently breaks query strings. Here is exactly when to use each one.
URLs can only contain a limited set of characters. Anything else — spaces, accented letters, and reserved symbols like & or ? — must be percent-encoded into %XX escape sequences. JavaScript gives you two functions for this, and choosing the wrong one is a classic source of broken links.
encodeURI — for a whole URL
encodeURI() assumes you are passing a complete, valid URL. It leaves the characters that give a URL its structure intact: : / ? # [ ] @ & = + $ , and a few others. Use it when you have a full address that just needs unsafe characters (like spaces) cleaned up.
encodeURIComponent — for a single value
encodeURIComponent() escapes far more aggressively, including / ? & = and #. Use it for individual pieces you are inserting into a URL — most importantly, query-string values.
Why the difference matters
Imagine a query value that itself contains an ampersand, like the search term "salt & pepper". If you use encodeURI, the & survives and the server reads it as a parameter separator, splitting your value in two. encodeURIComponent escapes it to %26, keeping the value whole.
Rule of thumb: encode the whole URL with encodeURI, but encode each individual query value with encodeURIComponent before you assemble the string.
Decoding
The matching functions decodeURI and decodeURIComponent reverse the process. A lone % that is not part of a valid escape will throw an error — a common reason decoding fails.
Try it
The URL Encoder / Decoder lets you switch between component and full-URL modes so you can see exactly what each produces before you ship it.