encodeURI vs encodeURIComponent: which should I use?

Dark navy cover card with the title 'encodeURI vs encodeURIComponent: which should I use?' in white and a green accent bar

Use encodeURIComponent() for any single value you put into a URL: a query parameter, a path segment, a value that is itself a URL. Use encodeURI() only on a complete URL that is already well formed, to escape stray spaces and non-ASCII characters without breaking its structure. When in doubt between encodeURI vs encodeURIComponent, pick encodeURIComponent, or let URL and URLSearchParams do the encoding for you.

What is the difference between encodeURI and encodeURIComponent?

The difference is the set of URL syntax characters each one leaves alone. encodeURI() keeps ; / ? : @ & = + $ , # as they are, because those characters give a URL its structure. encodeURIComponent() escapes them.

According to MDN's encodeURI page, both functions leave the same base set untouched: A–Z a–z 0–9 - _ . ! ~ * ' ( ). Everything else becomes UTF-8 percent-escapes, such as %20 for a space.

From MDN's comparison:

encodeURI(";/?:@&=+$,#");          // ";/?:@&=+$,#"
encodeURIComponent(";/?:@&=+$,#"); // "%3B%2C%2F%3F%3A%40%26%3D%2B%24%23"

encodeURI("ABC abc 123");          // "ABC%20abc%20123"
encodeURIComponent("ABC abc 123"); // "ABC%20abc%20123"

Those reserved characters match the delimiters in RFC 3986, which splits them into "gen-delims" like / ? # and "sub-delims" like & = +.

Why encodeURI breaks query values

encodeURI() breaks query values because it won't escape & or =, so a value that contains them gets split into extra parameters. MDN's example uses the name "Ben & Jerry's":

const name = "Ben & Jerry's";

encodeURI(`https://example.com/?choice=${name}`);
// "https://example.com/?choice=Ben%20&%20Jerry's"
// parsed: [["choice", "Ben "], [" Jerry's", ""]]

`https://example.com/?choice=${encodeURIComponent(name)}`;
// "https://example.com/?choice=Ben%20%26%20Jerry's"
// parsed: [["choice", "Ben & Jerry's"]]

With encodeURI, the server sees a choice of "Ben " and a second, empty parameter called " Jerry's".

The same thing happens with ?, # and / inside a value. I ran this in Node.js v24.15.0:

encodeURIComponent("a/b?c=d&e"); // "a%2Fb%3Fc%3Dd%26e"

Which one to use: a decision table

Pick the function by what the string is, not by where it ends up.

You are encoding Use Why
A whole URL you trust, with a stray space or accent encodeURI() Keeps / ? & # working
One query parameter value encodeURIComponent() or URLSearchParams Escapes &, =, # inside the value
One path segment, like a file name encodeURIComponent() Escapes / so it stays one segment
A URL passed as a parameter (?redirect=) encodeURIComponent() or URLSearchParams The inner ? and & must not leak out
A form body (application/x-www-form-urlencoded) URLSearchParams Writes spaces as +, as forms expect
A URL that is already percent-encoded Neither Encoding again doubles the %

Path segments are the case people forget. Say a user uploads a file called "Q3 report/final.pdf". With encodeURI, the slash survives and the server looks for a folder called "Q3 report":

const f = "Q3 report/final.pdf";
encodeURI("https://files.test/docs/" + f);
// "https://files.test/docs/Q3%20report/final.pdf"
"https://files.test/docs/" + encodeURIComponent(f);
// "https://files.test/docs/Q3%20report%2Ffinal.pdf"

My take: don't call either function directly in new code. Build the URL with the URL object and set values through searchParams, which escapes everything for you:

const u = new URL("https://example.com/search");
u.searchParams.set("redirect", "https://a.test/?x=1&y=2");
u.href;
// "https://example.com/search?redirect=https%3A%2F%2Fa.test%2F%3Fx%3D1%26y%3D2"

Spaces: %20 or +?

Both encodeURI() and encodeURIComponent() turn a space into %20. HTML forms use + for a space instead, and that is what URLSearchParams writes.

The WHATWG URL Standard defines that form format: a space becomes +, and a real plus becomes %2B. In Node, new URLSearchParams({ q: "a b&c" }).toString() gives q=a+b%26c.

MDN's encodeURIComponent page suggests replacing %20 with + afterwards if you must send form-encoded data by hand. The reverse problem, decoding + back into a space, is covered in decoding URLs with plus signs as spaces.

Common mistakes with both functions

Most encoding bugs come from encoding the wrong thing, or encoding the same thing twice.

  1. Encoding an already-encoded URL. encodeURI() escapes %, so encodeURI("https://example.com/caf%C3%A9") returns .../caf%25C3%25A9. The server then sees the literal text %C3%A9 instead of "é". Encode raw values once, at the point where you build the URL.
  2. Running encodeURIComponent on the whole URL. The : and / after https become %3A%2F%2F, and the result is no longer a link.
  3. Lone surrogates. Both functions throw URIError: malformed URI sequence on a broken UTF-16 string such as "\uD800". MDN points to toWellFormed(), which swaps lone surrogates for U+FFFD, and isWellFormed() to check first.
  4. Expecting RFC 3986 strictness. encodeURIComponent leaves ! ' ( ) * unescaped, although RFC 3986 reserves them. If an API signs the exact URL, use MDN's encodeRFC3986URIComponent helper:
function encodeRFC3986URIComponent(str) {
  return encodeURIComponent(str).replace(
    /[!'()*]/g,
    (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
  );
}

The limitation of all of these: percent-encoding is not a security boundary. It keeps your URL parseable. It does not make a user-supplied redirect target safe, and it does nothing for HTML output, which needs HTML escaping instead.

Binary data has its own rules on top of this. If you are putting Base64 into a URL, read Base64 vs Base64URL first, and for text with emoji or accents see encoding Unicode to Base64 in JavaScript.

FAQ

What is the difference between encodeURI and encodeURIComponent?

encodeURI leaves the URL syntax characters ; / ? : @ & = + $ , # alone, so it can run over a whole URL. encodeURIComponent escapes those too, so it is the one for a single value inside a URL.

Does encodeURIComponent encode spaces as + or %20?

It encodes a space as %20. Form encoding uses + instead, which is what URLSearchParams produces.

Should I use encodeURIComponent for the whole URL?

No. It escapes the slashes, colon and question mark, so https://example.com/ stops working as a link. Encode each dynamic part and leave the structure alone.

Why does encodeURIComponent throw URIError: malformed URI sequence?

The string has a lone UTF-16 surrogate. Call toWellFormed() on it first, or check it with isWellFormed().

Sources