skip to content

In JavaScript, what is the difference between encodeURI and encodeURIComponent, and which do you use for a value placed inside a query string?

level: juniorimportance: should knowfreq 42%

answer

  1. which punctuation survives
  2. the ampersand in a value
  3. whole URL versus one piece
  4. both escape the percent sign

basics

~20 s

encodeURI is for an already assembled URL and leaves URL syntax such as / ? & = # alone. encodeURIComponent also escapes those characters, so it is the one for a single dynamic value such as a query parameter.

solid answer

~50 s

Both functions turn characters into UTF-8 percent sequences, and both leave letters, digits and `- _ . ! ~ * ' ( )` untouched. The difference is a second set: `encodeURI` also leaves `; / ? : @ & = + $ , #` alone because they may be URL syntax, while `encodeURIComponent` escapes them. So I run `encodeURIComponent` on each dynamic piece before assembling the URL. If you call `encodeURI` on a URL with a user's value already in it, the `&` in `Ben & Jerry's` stays literal and starts a new parameter, and the `#` in `C#` turns the rest into a fragment. Calling `encodeURIComponent` on a whole URL breaks the other way, turning `https://` into `https%3A%2F%2F`. Neither is safe to apply twice: both escape `%`, so `%20` becomes `%2520`. In browsers and Node, `URL` and `URLSearchParams` handle query values for you.

code

javascript · 7 lines
javascript
const s = ';/?:@&=+$,#';
console.log(encodeURI(s));          // ;/?:@&=+$,#
console.log(encodeURIComponent(s)); // %3B%2F%3F%3A%40%26%3D%2B%24%2C%23

const marks = "-_.!~*'()";
console.log(encodeURI(marks));          // -_.!~*'()
console.log(encodeURIComponent(marks)); // -_.!~*'()

go deeper

for a junior

Recall the one-line rule: encodeURIComponent for a value, encodeURI for a whole URL. Predict what happens to an ampersand in a user's search text under each function.

for a middle

Know the two character sets rather than a slogan, including what both leave alone, such as the apostrophe. Explain double encoding, and why a plus sign in a query value can arrive as a space.

for a senior

When a parameter goes missing or splits in production, inspect the raw URL for an unescaped ampersand or hash. Build URLs in one helper so that encoding happens exactly once, at the point of assembly.

for a principal

Standardise on one URL-building path, usually URL and URLSearchParams, and flag string-built URLs in review. The cost is a small migration; the gain is that encoding stops being a decision made per call site.

## What percent-encoding is for A URL has **structure** carried by certain characters: `/` separates path segments, `?` starts the query, `&` and `=` split parameters, and `#` starts the fragment. A value placed inside a URL may contain those same characters. **Percent-encoding** replaces a character with `%XX` sequences, one per UTF-8 byte, so the character travels as data rather than being read as structure. JavaScript has two global functions for this, and they differ only in which characters they leave alone. ## The two character sets | Characters | `encodeURI` | `encodeURIComponent` | |---|---|---| | Letters, digits | Left alone | Left alone | | `- _ . ! ~ * ' ( )` | Left alone | Left alone | | `; / ? : @ & = + $ , #` | **Left alone** | **Escaped** | | Space | `%20` | `%20` | | `%` | `%25` | `%25` | | `[` and `]` | `%5B`, `%5D` | `%5B`, `%5D` | | Non-ASCII, such as `é` | Escaped as UTF-8 | Escaped as UTF-8 | The `%` and bracket rows hold the surprises, since both functions escape them. `encodeURI` keeps URL syntax because it assumes it is looking at a **complete, well-formed URL**. `encodeURIComponent` assumes it is looking at **one piece of data**, where any such character is just a character. ## The bug each misuse causes **`encodeURI` over a URL that already contains a value.** It cannot tell which `&` you meant as structure: ```javascript const name = "Ben & Jerry's"; const bad = encodeURI(`https://example.com/?choice=${name}`); console.log(bad); // https://example.com/?choice=Ben%20&%20Jerry's const good = `https://example.com/?choice=${encodeURIComponent(name)}`; console.log(good); // https://example.com/?choice=Ben%20%26%20Jerry's ``` The first URL parses into two parameters, `choice` with the value `Ben ` and a second one named ` Jerry's`. A `#` is worse: `encodeURI('https://a.io/search?q=C#&lang=en')` keeps the `#`, so everything after it becomes the fragment and browsers do not send a fragment to the server. The server sees `q=C` and no `lang`. **`encodeURIComponent` over a whole URL.** It escapes the structure itself, giving `https%3A%2F%2Fa.io%2Fx%3Fy%3D1`, which is no longer a URL that goes anywhere. That form is correct only when the URL is itself a value, such as a redirect target inside another URL's query string. **`encodeURI` over a path value.** A file name such as `a/b c.pdf` needs `encodeURIComponent` too. `'/files/' + encodeURIComponent('a/b c.pdf')` gives `/files/a%2Fb%20c.pdf`, so the slash stays part of the name. `encodeURI` keeps the slash, and the server sees an extra path segment. ## The rule 1. Keep the URL's fixed parts as literal text. 2. Run `encodeURIComponent` on each **dynamic** piece: a query value, a query key, a single path segment. 3. Join them. Use `encodeURI` only when you hold a complete URL that needs tidying, typically for spaces or non-ASCII characters, and it has no user data with structural characters in it. ## Edge cases worth knowing - **Double encoding.** Both functions escape `%`, so encoding an already encoded value gives `%2520`. Encode raw values, exactly once. - **Apostrophes and parentheses survive.** `encodeURIComponent("Ben's")` keeps the `'`. That matters if the result goes into a context that gives `'` a meaning, such as a single-quoted HTML attribute; escaping for HTML is a separate step. - **The plus sign.** `encodeURI` leaves `+` alone, but form-style query decoding reads `+` as a space, so `q=a+b` arrives as `a b`. `encodeURIComponent` gives `a%2Bb`, which arrives intact. - **Spaces in forms.** Neither function produces `+` for a space. The `application/x-www-form-urlencoded` format uses it, so that format needs an extra replacement of `%20`. - **Non-string input.** `encodeURIComponent(undefined)` returns the text `undefined`, because the argument is first converted to a string. Check for a missing value yourself. - **Lone surrogates.** Both functions throw a `URIError` on a string containing a lone surrogate. Tidy such text with `toWellFormed()` first, or test it with `isWellFormed()`. - **Decoding mirrors encoding.** `decodeURI('%26')` stays `%26`, because `&` is in the set `encodeURI` leaves alone, while `decodeURIComponent('%26')` gives `&`. Pair each decoder with its own encoder. ## The modern alternative Hosts that provide `URL` and `URLSearchParams`, which includes browsers and Node, can build query strings without manual encoding: `url.searchParams.set('choice', name)` escapes the value correctly. Those APIs use the form format, so a space becomes `+`. You still need `encodeURIComponent` for values in path segments and when writing a URL by hand, so interviewers still ask about the distinction.

  • In JavaScript, why can the `+` that `encodeURI` leaves in `?q=a+b` reach a form-style query decoder as a space?
    `encodeURI` leaves `+` alone, and form-style decoding reads `+` as a space, so a decoder of that kind yields `a b`. The fix is `encodeURIComponent('a+b')`, which gives `a%2Bb` and decodes back to `a+b`. The `+` meaning a space comes from the query format rather than from the function, which is why URL path segments do not share the problem.
  • When can JavaScript's `encodeURIComponent` throw, and what do you do about it?
    It throws a `URIError` when the string contains a lone surrogate, a UTF-16 code unit that is not part of a high-low pair, since that has no valid UTF-8 form. `encodeURI` behaves the same way. A common source is text cut in the middle of a surrogate pair. Test with `isWellFormed()` or repair with `toWellFormed()`, which substitutes the replacement character, before encoding.

encodeURI is a clerk handed a finished address label: commas and slashes are the label's structure, so they stay. encodeURIComponent is a clerk handed one name to write on that label: any comma in it is just part of the name and gets escaped.

  • encodeURIComponent is simply the newer replacement for encodeURI.
  • encodeURI escapes an ampersand inside a query value.
  • encodeURIComponent escapes every non-alphanumeric character, apostrophes and parentheses included.
  • Both functions encode a space as a plus sign.
  • Encoding twice is harmless because existing escapes are skipped.
  • A complete URL passed through encodeURIComponent is still a URL a browser can follow.