encodeURIComponent vs encodeURI: Never Mix Them Up Again

These two functions look almost identical — yet choosing the wrong one is the #1 cause of broken query strings and 400 Bad Request errors.

The Critical Difference

encodeURI() assumes the string is a full URL and leaves slashes, colons, and question marks intact. encodeURIComponent() assumes the string is a single component (like a query value) and encodes everything that could break parsing — including &, ?, =, and /.

Real Example That Breaks

Search term: “cats & dogs” Correct: ?q=encodeURIComponent("cats & dogs") → ?q=cats%20%26%20dogs Wrong: ?q=encodeURI("cats & dogs") → ?q=cats%20&%20dogs → splits into q=cats and dogs= (empty)

Quick Rule of Thumb

  • Use encodeURI() only when building a complete URL from safe parts
  • Use encodeURIComponent() for every query parameter value and path segment
  • When in doubt → encodeURIComponent()

FAQ

Why does encodeURI exist at all?

For safely encoding entire URLs when you already know the structure is valid (rare in practice).

Does this tool use the correct one?

Yes — it always uses encodeURIComponent() + proper handling of reserved chars for maximum safety.

One wrong function call = hours of debugging. Bookmark this page.