← All Guides

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

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

Validate all of these cases in the URL Encoder/Decoder tool before shipping API integrations.