URL Encoding Guide: encodeURI vs encodeURIComponent
This is the bug pattern we see most in API calls: developers build query strings with raw values, then wonder why a name like Tom & Jerry breaks the request. The fix is simple once you separate full-URL encoding from value encoding.
Short Answer
- Use
encodeURIwhen you already have a complete URL and want to keep URL separators readable. - Use
encodeURIComponentfor each dynamic piece (query value, path fragment, token) before joining the final URL.
What Usually Goes Wrong
// Unsafe: `&` splits the parameter unexpectedly
const userInput = "Tom & Jerry";
const badUrl = "https://api.example.com/search?q=" + userInput;
// Safe: the value is encoded before insertion
const q = encodeURIComponent(userInput);
const goodUrl = `https://api.example.com/search?q=${q}`;
// https://api.example.com/search?q=Tom%20%26%20Jerry
Percent Encoding vs Plus Encoding
Browsers and frameworks may treat spaces differently. In standard URL encoding, spaces become %20. In form-style payloads (application/x-www-form-urlencoded), spaces may become +. Treat those as different contexts, not interchangeable defaults.
Related Cases
- How to encode spaces in URL values
- How to encode ampersands correctly
- When plus means space
- Unicode URL encoding examples
Validate all of these cases in the URL Encoder/Decoder tool before shipping API integrations.