encodeURI vs encodeURIComponent: When Each Function Applies
Choosing the wrong encoder silently corrupts URLs: a value containing & or = can be parsed as extra parameters, and whole-URL encoding makes a link unusable. Modern query-string handling via URLSearchParams removes the risk, so front-end code should stop manually splicing encoded values.
encodeURI and encodeURIComponent both percent-encode strings, but they treat URL structure differently. encodeURI preserves the characters that separate a URL's parts—colon, slash, question mark, ampersand, equals—so the output still looks like a URL. encodeURIComponent encodes those structural characters too, turning the whole string into a single encoded value. That's why encodeURI('https://example.com/a?x=1&y=2') stays intact while encodeURIComponent turns it into https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26y%3D2.
The distinction matters when building query strings. Encoding a parameter value with encodeURI leaves & and = untouched, which can inject extra parameters into the URL. Encoding 'JavaScript & sort=recent' with encodeURI yields q=JavaScript%20&%20sort=recent, changing the meaning. The recommended path for query parameters is URLSearchParams or encodeURIComponent for each value, not manual concatenation.
Double-encoding is another trap: calling encodeURIComponent on an already-encoded string turns %20 into %2520. URLSearchParams serializes spaces as + rather than %20, which is correct for query strings. The closing summary table puts the two functions side by side by target, preservation, and common use.
The failure case for encodeURI on parameter values is concrete and easy to reproduce; the example with & and = demonstrates the injection path in a few lines.
Because URLSearchParams handles encoding and separators automatically, the practical takeaway is to stop hand-building query strings entirely.