URL Encoding vs. Decoding: JavaScript encodeURI vs encodeURIComponent
Understand the difference between URL encoding and decoding, compare encodeURI vs encodeURIComponent in JavaScript, and avoid double-encoding pitfalls.
encodeURI vs. encodeURIComponent
JavaScript provides two distinct encoding functions with different scopes:
- encodeURI(): Intended for complete URLs. It preserves structural delimiters like
http://,/,?, and&. - encodeURIComponent(): Intended for individual query parameter values. It encodes all delimiters (e.g.
&becomes%26,/becomes%2F) so parameter values do not corrupt URL parsing.
Code Example: Proper Parameter Encoding
const baseUrl = "https://api.toolnest.dev/search";
const query = "developer tools & utilities / 2026";
// INCORRECT (breaks query delimiter):
const badUrl = `${baseUrl}?q=${query}`;
// CORRECT:
const goodUrl = `${baseUrl}?q=${encodeURIComponent(query)}`;
// Output: https://api.toolnest.dev/search?q=developer%20tools%20%26%20utilities%20%2F%202026