encodeURI vs encodeURIComponent

Understand the key differences between JavaScript's encodeURI() and encodeURIComponent(). Learn which to use for paths, parameters, and full URLs.

Detailed Explanation

JavaScript provides two built-in functions for URL encoding: encodeURI() and encodeURIComponent(). They serve different purposes and encode different sets of characters. Using the wrong one is a common source of bugs.

encodeURI() is designed for encoding a complete URI. It preserves characters that have structural meaning in a URL:

  • Does NOT encode: A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
  • Does encode: spaces, non-ASCII characters, and other unsafe characters

encodeURIComponent() is designed for encoding a single URI component (like a query parameter value). It encodes everything except unreserved characters:

  • Does NOT encode: A-Z a-z 0-9 - _ . ! ~ * ' ( )
  • Does encode: ; , / ? : @ & = + $ # and everything encodeURI() encodes

Side-by-side comparison:

const url = "https://example.com/path?q=hello world&lang=en";

encodeURI(url)
// "https://example.com/path?q=hello%20world&lang=en"
// Structure preserved, only spaces encoded

encodeURIComponent(url)
// "https%3A%2F%2Fexample.com%2Fpath%3Fq%3Dhello%20world%26lang%3Den"
// Everything encoded - the URL is now a single opaque value

When to use each:

Use encodeURI() when you have a complete URL with spaces or Unicode characters but the structure (scheme, host, path, query delimiters) is already correct. This is rare in practice.

Use encodeURIComponent() when encoding individual values to be placed into a URL: parameter values, path segments, or fragment identifiers. This is the function you need 95% of the time.

Best practice: Use URLSearchParams for query strings:

const params = new URLSearchParams({
  q: "hello world",
  url: "https://other.com/page?id=5",
  tags: "a&b"
});
const fullUrl = `https://api.example.com/search?${params}`;
// Handles all encoding automatically and correctly

Pitfall: Using encodeURI() on a parameter value will fail to encode critical characters like &, =, ?, and #, leaving the URL structurally broken. Conversely, using encodeURIComponent() on an entire URL will encode the :// and / characters, making the URL unusable. Always choose the function that matches your use case.

Use Case

Any JavaScript application that constructs URLs dynamically, from building API request URLs to generating shareable links with user-provided content.

Try It — URL Encoder

Open full tool