跪拜 Guibai
← All articles
Frontend

encodeURI vs encodeURIComponent: When Each Function Applies

By excel ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

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.

Summary

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.

Takeaways
— encodeURI preserves URL structural characters such as : / ? & = and #; encodeURIComponent encodes all of them.
— encodeURI on 'https://example.com/a?x=1&y=2' returns the same string; encodeURIComponent returns https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26y%3D2.
— Using encodeURI for a query parameter value leaves & and = intact, allowing unintended parameters: encoding 'JavaScript & sort=recent' produces q=JavaScript%20&%20sort=recent.
— encodeURIComponent on an already encoded string double-encodes the % sign: 'hello world' becomes hello%20world, then hello%2520world.
— URLSearchParams serializes spaces as + in query strings, not %20.
— URLSearchParams and URL objects replace manual concatenation for building query strings.
Conclusions

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.

Source: juejin.cn ↗ Google Translate ↗ Backup ↗