Every URL you build has two kinds of territory: the structure that makes it a URL at all — the scheme, the slashes, the question mark, the ampersands that separate parameters — and the values you place inside that structure. JavaScript gives you two functions for percent-encoding, and they differ in exactly one way: which of those territories they are willing to touch. encodeURI treats its input as a complete URL and protects the structure. encodeURIComponent treats its input as a single opaque value and encodes everything that could possibly be misread as structure.
That distinction sounds simple, and it is. Yet the two bugs it produces — a URL mangled by the wrong function, and a query value that quietly becomes several parameters — show up in production code constantly, because the difference only matters at a boundary, and boundaries are invisible when you stare at a string literal. This guide maps the territory precisely, walks through the failure modes in both directions, and ends with a decision rule plus a safer alternative that removes most of the decisions entirely.
Two different boundaries
A whole URL is a structure
Take a typical request URL:
https://api.example.com/search?q=blue shoes&page=2
It has a scheme (https:), a host, a path, and a query string with two parameters separated by &. Those characters are not data — they are the skeleton. If you percent-encode the skeleton, the URL stops being a URL: %3A%2F%2F is not a scheme followed by two slashes, it is a run of inert text. A function that accepts a whole URL must therefore leave every structural character exactly where it is and escape only the stray characters that should never appear raw in a URL — a space, a quote, a non-ASCII letter.
A component value is an opaque string
Now look at the other boundary. Suppose the value of q is whatever a user typed into a search box: blue shoes & hats. From the moment this string becomes a parameter value, every character in it is data. Its ampersand must not be confused with the ampersand that separates parameters. Its spaces must not break the request line. Its equal signs, question marks, and slashes must all be smuggled through as inert text. A function that accepts a single component must therefore be aggressive: it escapes everything except the characters that are unconditionally safe everywhere.
encodeURI is built for the first boundary. encodeURIComponent is built for the second. Nearly every encoding bug is one of these functions applied across the wrong boundary line.
What each function leaves alone
encodeURI preserves the full set of structural characters: the alphanumerics, of course, plus ; , / ? : @ & = + $ # and the small group of unreserved marks - _ . ! ~ * ' ( ). Those are the characters RFC 3986 allows to appear raw in the various parts of a URI, and leaving them untouched is exactly what lets a complete URL survive encoding with its meaning intact. One wrinkle: modern engines do escape the square brackets used around IPv6 hosts, though behavior varied across older runtimes — worth remembering if you build URLs containing literal IPv6 addresses.
encodeURIComponent keeps only the alphanumerics and - _ . ! ~ * ' ( ). Everything else — including all the structural punctuation — becomes %XX sequences. The characters it spares beyond alphanumerics are legacy-safe: they are sub-delimiters in RFC 3986, but they carry no special meaning inside a query value, so leaving them raw is harmless. The practical reading is simpler: encodeURIComponent escapes every character that could be mistaken for URL structure, which is precisely the contract you want at the value boundary.
A character-by-character comparison
The two functions agree on most input and disagree exactly where it matters:
| Input | encodeURI | encodeURIComponent |
|---|---|---|
| A–Z a–z 0–9 | unchanged | unchanged |
- _ . ~ ! * ' ( ) | unchanged | unchanged |
: / ? # | unchanged | %3A %2F %23 |
& = + $ ; , @ | unchanged | %26 %3D %2B %24 %3B %2C %40 |
[ ] | %5B %5D (modern engines) | %5B %5D |
| space | %20 | %20 |
" < > \ ^ { | } | %22 %3C %3E %5C %5E %7B %7C %7D | same |
% | %25 | %25 |
é | %C3%A9 | %C3%A9 |
| 😀 (U+1F600) | %F0%9F%98%80 | %F0%9F%98%80 |
Both functions percent-encode using UTF-8 bytes, which is why é becomes two bytes and an emoji becomes four. That behavior is consistent and correct for the modern web; there is no reason to reach for legacy escape-based tricks.
Bug #1: encodeURIComponent on a whole URL
The classic mistake is feeding a complete URL to encodeURIComponent, usually by accident when a URL and a value end up concatenated in the same expression:
encodeURIComponent("https://api.example.com/search?q=blue shoes");
// "https%3A%2F%2Fapi.example.com%2Fsearch%3Fq%3Dblue%20shoes"
Every structural character is gone. The colon and slashes that made this a URL are now %3A and %2F, and the query string has dissolved into one long parameter value. Hand that string to fetch or drop it into an href and the request goes somewhere you did not intend — usually a 404, occasionally a silent wrong-route match on the server.
encodeURI on the same input does the right thing, because the space is the only character that violates URL syntax:
encodeURI("https://api.example.com/search?q=blue shoes&page=2");
// "https://api.example.com/search?q=blue%20shoes&page=2"
The skeleton survives; only the illegal character is escaped. If your input is genuinely a complete, mostly well-formed URL, encodeURI is the right tool. The operative word is mostly — see the next section for why that caveat carries weight.
Bug #2: encodeURI on a query value
The mirror-image bug is subtler and often worse, because nothing fails loudly. Put a value containing & or = into a query string using encodeURI:
const tag = "sale&clearance";
encodeURI("https://api.example.com/items?tag=" + tag);
// "https://api.example.com/items?tag=sale&clearance"
encodeURI deliberately preserved the ampersand, so the server parses two parameters: tag=sale and a valueless parameter named clearance. A filter intended to match one tag now matches whatever tag=sale happens to return, and the stray parameter is ignored — or worse, collides with a real parameter name. There is no error and no stack trace, just quietly wrong results that a test suite built around well-behaved fixtures will never catch.
The fix is to encode at the value boundary, not the URL boundary:
const tag = "sale&clearance";
"https://api.example.com/items?tag=" + encodeURIComponent(tag);
// "https://api.example.com/items?tag=sale%26clearance"
Now the ampersand is data — %26 — and the server reconstructs the original single value. The same rule covers =, +, #, and ? appearing inside any parameter value, path segment, or fragment you compose by hand.
Spaces, plus signs, and %2B
Nothing causes more confusion in query strings than the humble plus sign, because + has two different meanings depending on which tradition is reading the URL.
In the application/x-www-form-urlencoded media type — the encoding that HTML forms and most server frameworks use when they parse query strings — a + represents a space. In generic URI syntax, however, RFC 3986 gives + no such meaning: it is an ordinary sub-delimiter, free to mean whatever a given API decides it means. The two conventions coexist, and they collide regularly.
This produces a well-known failure: you encode a literal plus sign with encodeURIComponent, producing %2B, but the receiving form-parser decodes bare + as a space — and depending on when percent-decoding happens in that server's pipeline, %2B can come back as a space too. A user's search for C++ arrives as C followed by nothing useful. The defensive fix is the same either way: make sure any literal + in a value is percent-encoded as %2B, and confirm how the server decodes it. If you control the API, document the convention. If you do not, test it with a +, a space, and %2B before you build anything on top of it.
Spaces themselves are another trap: %20 is always correct in a query string, a raw space is technically illegal, and a bare + means space only in form-encoded contexts. When you see %20 and + mixed in one query string, someone has assembled it from sources that disagree about the convention.
Double encoding: the %2520 smell
Percent-encoding is not idempotent. Encoding an already-encoded value encodes the percent signs themselves:
const value = "blue shoes"; // needs encoding
const once = encodeURIComponent(value); // "blue%20shoes"
const twice = encodeURIComponent(once); // "blue%2520shoes"
%2520 is the tell. It decodes to the literal text %20, which means the server will see percent-twenty rather than a space. Double encoding happens when a value passes through two layers that each assume they are the first to encode it — a client encodes, a proxy or template layer encodes again, or a framework already encodes parameters and you encode them yourself before handing them over. The result ranges from failed lookups to literal %20 appearing in rendered output.
Escaping has the same layered pathology in other formats; the fix pattern is identical to the one for escapes inside structured strings such as JSON Pointer tokens: decide which layer owns the escaping and let exactly one layer do it. To detect double encoding, decode once and inspect the result. If it still contains % sequences that look meaningful — %20, %2F, %26 — the value was encoded more than once.
To detect double encoding mechanically, test the value for percent signs that themselves appear encoded — a %25 immediately followed by two hex digits is almost never legitimate data:
function looksDoubleEncoded(s) {
return /%25[0-9A-Fa-f]{2}/.test(s);
}
looksDoubleEncoded("blue%2520shoes"); // true — encoded twice
looksDoubleEncoded("blue%20shoes"); // false — encoded once
Never "fix" double encoding by calling decodeURIComponent on input as a blind first step. If a value legitimately contains percent signs as data, stripping a decode layer corrupts it. Encode exactly once, at the boundary where the value enters the URL.
The decode side of the coin
Each function has a counterpart: decodeURI and decodeURIComponent. The pairing rule matches the encode side — decode with the function that corresponds to how the value was encoded. Decoding a component value that was processed with encodeURIComponent requires decodeURIComponent; using decodeURI leaves %26, %3D, and friends intact, because those encode reserved characters it refuses to touch.
decodeURI is also not an unconditional inverse of encodeURI. It declines to decode sequences that would produce structural characters, precisely so that decoding a whole URL cannot accidentally splice new & or / into the structure. That safety is useful, but it means decodeURI is rarely the tool you want when handling a single value:
decodeURI("tag%3Dsale%26clearance");
// "tag%3Dsale%26clearance" — nothing decoded
decodeURIComponent("tag%3Dsale%26clearance");
// "tag=sale&clearance" — the original value
One more asymmetry to respect: decodeURIComponent throws a URIError on malformed sequences, such as a stray % not followed by two hex digits. Values arriving from the outside world — query strings, redirects, fragments — should be decoded inside a try/catch, never trusted to be well-formed.
Building URLs piece by piece with URLSearchParams
Once a URL has more than one parameter, the encode-each-value-by-hand pattern invites exactly the mistakes described above. The URLSearchParams API removes the decisions by taking values as opaque data and serializing the whole set correctly:
const params = new URLSearchParams();
params.set("q", "blue shoes & hats");
params.set("page", "2");
params.set("tag", "C++");
const url = "https://api.example.com/search?" + params.toString();
// "https://api.example.com/search?q=blue+shoes+%26+hats&page=2&tag=C%2B%2B"
Note what it did: the ampersand inside the value became %26, the literal plus signs became %2B, and spaces became + per the form-urlencoded convention that virtually every server query parser accepts. Reading values back is symmetric:
new URLSearchParams("q=blue+shoes+%26+hats").get("q");
// "blue shoes & hats"
URLSearchParams handles the query portion only — the scheme, host, and path still need care. Path segments built from user data should be encoded individually with encodeURIComponent, with one caveat: it escapes /, which is usually what you want for a single segment but will mangle a value that legitimately contains slashes, such as a date range. For a whole existing URL where you merely want illegal characters tidied up, encodeURI remains the appropriate one-shot tool.
Path segments: the third boundary
Query values are not the only place a component can hide. Path segments deserve their own mention, because they fail differently. A segment such as a filename or a record slug is a single value, so it belongs to encodeURIComponent — but it is joined into the URL between slashes that must remain structural. The safe pattern is to encode each segment individually and join the results, never to encode the assembled path:
const owner = "acme corp";
const repo = "api docs";
"https://api.example.com/repos/" + encodeURIComponent(owner) + "/" + encodeURIComponent(repo);
// "https://api.example.com/repos/acme%20corp/api%20docs"
Encode the whole path at once and the slashes separating segments would be escaped along with everything else; encode nothing and a space or slash inside a segment changes how many segments the server sees. The same per-segment discipline applies to fragments and to anything templated into a URL by a string interpolation — the boundary is always the individual value, and it is always worth locating before the first percent sign is written.
Non-ASCII and emoji in components
Both functions percent-encode non-ASCII text as UTF-8 bytes, which is the modern, correct behavior:
encodeURIComponent("café ☕");
// "caf%C3%A9%20%E2%98%95"
é is two bytes (C3 A9); the emoji is four. The server percent-decodes the bytes and reconstructs the same characters, so round-tripping is lossless as long as both sides treat the payload as UTF-8. Two practical notes follow. First, a visible character and its percent-encoded form name the same resource — /caf%C3%A9 and /café are the same path — so canonicalize consistently if you use URLs as keys. Second, beware environments that operate on raw bytes or assume Latin-1; a framework that decodes %C3%A9 into two separate characters instead of one will mangle every non-ASCII value it receives. When parameters carry structured text rather than plain values, the encoding rules change entirely — headers being the classic example, as covered in JSON in HTTP headers.
A decision rule you can keep
The whole guide compresses to one question: what is the boundary of the string you are about to encode?
If the string is a complete URL and you only want to make it legal, use encodeURI. It preserves every structural character and escapes the strays. If the string is one value destined for a URL — a query parameter, a path segment, a fragment — use encodeURIComponent, and place the call so it covers exactly the value and none of the surrounding structure. If you are composing a query string from multiple values, skip both and use URLSearchParams. If you are decoding, match the decode function to whoever did the encoding, wrap it in error handling, and treat any %25 you spot as evidence that a second encoding layer crept in somewhere.
And when a request built this way fails on the server, resist the urge to keep re-encoding until it works. A structured error response will usually tell you exactly which part of the URL was rejected; the patterns in problem-details errors are worth knowing for precisely those moments. Encoding bugs thrive on guesswork. The boundary question, asked once, removes it.
Test it yourself: paste a URL and a few parameter values into the URL Workbench, encode them with both functions, and watch which characters survive. Five minutes of side-by-side comparison will make the boundary line harder to forget than any table in this guide.
Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.