URL Encoding Explained: When and Why to Percent-Encode
Why certain characters must be encoded in URLs, the difference between encodeURI and encodeURIComponent, and when double-encoding happens.
URL encoding converts characters that are unsafe in URLs into a percent sign followed by their hexadecimal representation. Understanding when and how to encode is essential for reliable APIs, redirects, and user input handling.
Why URL encoding is necessary
URLs can only contain a limited set of ASCII characters. Characters like spaces, ?, #, and non-ASCII text would break URL parsing if included literally.
Percent-encoding replaces each unsafe byte with %XX where XX is its hexadecimal value. A space becomes %20, a question mark becomes %3F, and the Japanese character 日 becomes %E6%97%A5 based on its UTF-8 byte sequence.
Tools for this section
encodeURI vs encodeURIComponent
encodeURI is designed for full URLs and deliberately preserves structural characters such as /, ?, =, and &. Use it when you already have a complete URL and only need to escape unsafe characters.
encodeURIComponent is designed for partial values such as query parameters or redirect targets. If you are encoding just one parameter value, this is usually the safer choice.
Tools for this section
Double-encoding and how to avoid it
Double-encoding happens when an already encoded string gets encoded again. %20 becomes %2520 because the % itself is encoded as %25.
The most common cause is passing a complete URL through encodeURIComponent instead of encoding only the parameter value that needs escaping. Keep the encoding boundary small and explicit.
Tools for this section