JavaScript has two functions for percent-encoding text, and choosing the wrong one is one of the most common URL bugs. Both convert unsafe characters to UTF-8 bytes written as %XX. The only difference is which characters they leave alone, and that difference decides whether your URL survives.
Every output on this page was produced by running the functions while the page was built, not copied from documentation.
The rule in one line
encodeURIComponentis for a part: a query value, a key, a path segment, a fragment. It encodes everything that could change the meaning of a URL.encodeURIis for a whole URL that is already structured correctly but contains characters such as spaces or non-English letters. It keeps the characters that give a URL its structure.
If you are building a URL from pieces, which is almost always the case, you want encodeURIComponent on each piece, or URLSearchParams, which does it for you.
What each one encodes
The same characters through both functions. Where the output equals the input, the function kept the character.
| Character | encodeURI | encodeURIComponent | Role in a URL |
|---|---|---|---|
| space | %20 | %20 | Not allowed; must be encoded |
| / | kept | %2F | Separates path segments |
| ? | kept | %3F | Starts the query |
| # | kept | %23 | Starts the fragment |
| & | kept | %26 | Separates query parameters |
| = | kept | %3D | Separates a key from its value |
| + | kept | %2B | Space in form-encoded queries |
| : | kept | %3A | After the scheme; before the port |
| @ | kept | %40 | Separates user info from the host |
| , | kept | %2C | Sub-delimiter |
| ; | kept | %3B | Sub-delimiter |
| $ | kept | %24 | Sub-delimiter |
| ! | kept | kept | Sub-delimiter (RFC 3986) |
| ' | kept | kept | Sub-delimiter (RFC 3986) |
| ( | kept | kept | Sub-delimiter (RFC 3986) |
| ) | kept | kept | Sub-delimiter (RFC 3986) |
| * | kept | kept | Sub-delimiter (RFC 3986) |
| ~ | kept | kept | Unreserved |
| % | %25 | %25 | Starts an escape sequence |
| é | %C3%A9 | %C3%A9 | Non-ASCII; encoded as UTF-8 |
| € | %E2%82%AC | %E2%82%AC | Non-ASCII; encoded as UTF-8 |
The pattern is clear: encodeURI keeps ; , / ? : @ & = + $ #, the reserved characters that separate a URL into scheme, host, path, query and fragment. encodeURIComponent encodes all of them. Both keep letters, digits and - _ . ! ~ * ' ( ), and both encode %, spaces and non-ASCII characters as UTF-8.
How encodeURI breaks a query value
Suppose a user searches for Tom & Jerry and you encode the finished URL:
encodeURI("https://example.com/search?q=Tom & Jerry&page=1")
// "https://example.com/search?q=Tom%20&%20Jerry&page=1"The space was encoded, but the & inside the search term was not. A server now sees three parameters instead of two:
[...new URL(encodeURI("https://example.com/search?q=Tom & Jerry&page=1")).searchParams]
// [["q","Tom "],[" Jerry",""],["page","1"]]The search term was cut to Tom. Encoding the value on its own fixes it, because encodeURIComponent encodes the ampersand:
"https://example.com/search?q=" + encodeURIComponent("Tom & Jerry") + "&page=1"
// "https://example.com/search?q=Tom%20%26%20Jerry&page=1"The same failure happens with =, + and # in a value. A # is the worst: encodeURI keeps it, so everything after it becomes the fragment and is never sent to the server.
How encodeURIComponent breaks a whole URL
The opposite mistake encodes the separators themselves:
encodeURIComponent("https://example.com/a b?x=1")
// "https%3A%2F%2Fexample.com%2Fa%20b%3Fx%3D1"That is no longer a usable address. It is exactly what you want, though, when the whole URL is itself a value, for example a redirect or returnTo parameter:
"/login?returnTo=" + encodeURIComponent("/cart?item=42&qty=2")
// "/login?returnTo=%2Fcart%3Fitem%3D42%26qty%3D2"Without the encoding, qty=2 would become a parameter of the login page instead of part of the return address. Open this example in the decoder to see the layers.
Do not encode twice
Both functions encode the percent sign itself. Running either on text that is already encoded corrupts it:
encodeURI("https://example.com/a%20b")
// "https://example.com/a%2520b"%2520 is the signature of double encoding; the %25 page explains how to recognise and undo it. Keep raw text raw until the moment you place it into a URL, and encode it exactly once there.
decodeURI vs decodeURIComponent
The decoding functions mirror the encoders. Here is the same input through both:
decodeURI("%2F %3F %26 %41 %20")
// "%2F %3F %26 A "
decodeURIComponent("%2F %3F %26 %41 %20")
// "/ ? & A "decodeURI decoded %41 and %20 but left %2F, %3F and %26 encoded, because decoding them would change the structure of the URL. That makes decodeURI useful for one job only: turning a URL into something readable for display while keeping it valid. To read a value, use decodeURIComponent on that value after splitting the URL, or let URL and URLSearchParams do it.
Two details are worth knowing:
- Neither function treats
+as a space:decodeURIComponent("a+b")returns"a+b". Form data and many query strings use+for spaces, so decode those withURLSearchParams. The space guide covers this in depth. - Both throw
URIErroron a malformed sequence, such as a lone%or bytes that are not valid UTF-8. See how to fix URI malformed.
The five characters encodeURIComponent keeps
encodeURIComponent leaves ! ' ( ) * unencoded. JavaScript inherited that from RFC 2396, where they were unreserved. RFC 3986, the current standard, made them reserved sub-delimiters. Most servers accept them either way, but some strict APIs and OAuth 1.0 signature schemes require every reserved character to be encoded. MDN documents a small helper for that case:
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
encodeRFC3986URIComponent("a!b'c(d)e*")
// "a%21b%27c%28d%29e%2A"Errors you can hit when encoding
Encoding rarely fails, with one exception: a lone surrogate. JavaScript strings are UTF-16, and an emoji is stored as a pair of surrogates. Cutting a string in the middle of a pair, for example with slice, leaves half of one, which has no UTF-8 form:
encodeURIComponent("😀".slice(0, 1))
// URIError: URI malformedIf you truncate user input before encoding it, cut with Array.from(str).slice(…), which splits by code points, or check with str.isWellFormed() where your runtime supports it.
Better: let the URL API encode for you
Modern JavaScript, in every current browser and in Node.js, has URL and URLSearchParams. They encode each part with the right rules, so you never pick a function by hand:
const url = new URL("https://example.com/search");
url.searchParams.set("q", "Tom & Jerry");
url.searchParams.set("page", "1");
url.href
// "https://example.com/search?q=Tom+%26+Jerry&page=1"Note the + for the spaces: URLSearchParams uses form encoding. Every server-side query parser reads that as a space. The URLSearchParams guide covers the API in full, including the cases where it surprises people.
The equivalents in other languages
Other languages split the same job differently, and their defaults do not match JavaScript's. Here is a b/c?d=é through the closest equivalents. Outputs come from running each runtime.
| Language | Function | Output |
|---|---|---|
| JavaScript | encodeURIComponent | a%20b%2Fc%3Fd%3D%C3%A9 |
| JavaScript | encodeURI | a%20b/c?d=%C3%A9 |
| Python | urllib.parse.quote(s, safe='') | a%20b%2Fc%3Fd%3D%C3%A9 |
| Python | urllib.parse.quote(s) | a%20b/c%3Fd%3D%C3%A9 |
| C# | Uri.EscapeDataString | a%20b%2Fc%3Fd%3D%C3%A9 |
Python's quote keeps / by default, so it behaves like neither JavaScript function; pass safe='' to encode a component. C#'s Uri.EscapeDataString is the component encoder. The function comparison shows every character across ten functions.
Checklist
- Building a URL from parts: encode each part with
encodeURIComponent, or useURLandURLSearchParams. - Putting a URL inside another URL:
encodeURIComponenton the inner URL. - Cleaning up a complete URL that has spaces or accents:
encodeURI, but only if it is not already encoded. - Reading a value: split first, then decode the value once.
- Never use
escapeorunescape.
To check a result by hand, paste it into the URL Decoder or build one with the URL Encoder, which offers both component and full-URL scopes.