Why URLs need encoding
URLs may only contain a limited set of ASCII characters. Spaces, non-Latin letters and characters with special meaning (? & = # /) must be percent-encoded as % followed by two hex digits of each UTF-8 byte. A space becomes %20, and é becomes %C3%A9.
encodeURIComponent vs encodeURI
- Encode component (
encodeURIComponent) escapes everything except letters, digits and- _ . ! ~ * ' ( ). Use it for individual query values and path segments. - Encode full URL (
encodeURI) leaves separators such as: / ? & = #intact. Use it only on a complete URL that's already structured correctly.
The plus sign
In HTML form submissions (application/x-www-form-urlencoded), spaces are encoded as +. This decoder treats + as a space. In modern code, prefer URLSearchParams, which handles all of this correctly.