ToolPane
Blog

encodeURI vs encodeURIComponent

Understand the difference between encodeURI and encodeURIComponent in JavaScript and when to use each.

Open URL Encoder

The Key Difference

JavaScript ships two URL-encoding functions, and using the wrong one is the most common URL bug. encodeURI() is for encoding a complete URL — it preserves the characters that give a URL its structure (: / ? # [ ] @ ! $ & ' ( ) * + , ; =) so the URL still works. encodeURIComponent() is for encoding a single value that goes inside a URL — it encodes those structural characters too, so a value containing & or = can't break out and corrupt the query string. Rule of thumb: encode the whole URL with encodeURI, encode each piece you insert with encodeURIComponent.

When to Use Each

  • Use encodeURIComponent() for query parameter values, path segments, and any user data you splice into a URL.
  • Use encodeURI() only when you have an already-structured URL with a space or non-ASCII character and want to make it valid without touching its structure.
  • Common mistake: encodeURI("a=1&b=2") leaves & and = unencoded — wrong for a parameter value.
  • Difference in characters: encodeURIComponent additionally encodes , / ? : @ & = + $ #.
  • Decoding: pair them with decodeURI and decodeURIComponent respectively.
const url = "https://api.test/search";
const q = "Tom & Jerry";

// WRONG — & breaks the query string
encodeURI(`${url}?q=${q}`);
// ".../search?q=Tom%20&%20Jerry"

// RIGHT — value encoded independently
`${url}?q=${encodeURIComponent(q)}`;
// ".../search?q=Tom%20%26%20Jerry"