encodeURI vs encodeURIComponent: Key Differences and Pitfalls
JavaScript provides two built-in functions to encode Uniform Resource Identifiers (URIs): encodeURI and encodeURIComponent. Understanding when to use which is critical to avoid broken links and malformed parameters.
encodeURI
encodeURI is designed to encode a complete URI. It assumes that the URI is already fully formed (e.g. https://example.com/search?q=value), so it does not encode characters that have special meaning in a URI structure:
- Preserves:
;,,,/,?,:,@,&,=,+,$,#
Example:
encodeURI("https://example.com/search?q=hello world")
// -> "https://example.com/search?q=hello%20world"URL Encoder / Decoder
Encode or decode URLs and URI query parameters online. Safely format special characters, spaces, and reserved symbols client-side with full UTF-8 support.
encodeURIComponent
encodeURIComponent is designed to encode a segment or query parameter of a URI. It escapes almost all characters, including structural URI separators:
- Escapes:
/,?,:,@,&,=,+,$,#
Example:
encodeURIComponent("https://example.com/search?q=hello world")
// -> "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dhello%20world"When to Use Which?
- Use encodeURI when you want to sanitize a full URL while keeping its routing slashes and query separators intact.
- Use encodeURIComponent when you want to sanitize dynamic parameter values that will be appended inside a query string (e.g.
?query=${param}).