URL Encoding (Percent-Encoding) Explained: encodeURIComponent, Spaces, and Double Encoding
URLs can only contain a limited set of characters. To include anything else, such as spaces, accented letters, or symbols with special meaning, they are converted to percent-encoding: a percent sign followed by two hexadecimal digits representing the byte. How it works Text is first converted to bytes using UTF-8, and each byte that isn't allowed is written as %XX. A space is the byte 0x20, so it…
URLs cannot contain every character you need. To represent spaces, accented letters, or other symbols with special meanings, they undergo percent-encoding. This process involves converting text into bytes using UTF-8 and then encoding each disallowed byte as %XX. A space, which is the byte 0x20, translates to %20. The letter e with an acute accent requires two UTF-8 bytes and becomes %C3%A9.
For example, "hello world" becomes "hello%20world", "a&b=c" becomes "a%26b%3Dc", and "café" becomes "caf%C3%A9". Certain characters like : / ? # [ ] @ ! $ & () * + , ; = have specific roles in URLs, so if you want to use one of these characters as data, it must also be encoded to avoid confusion with URL structure.
There are two main functions for encoding in URLs: encodeURI and encodeURIComponent. encodeURI encodes an entire URL but leaves structural characters like : / ? & = # unchanged, which is why it should be used for the full URL rather than individual values. encodeURIComponent, on the other hand, encodes a single value and encodes the structural characters, making it suitable for query parameters or path segments.
When constructing a URL with query parameters in an HTML form (application/x-www-form-urlencoded), spaces are represented as + in the encoded query string. However, in other parts of a URL or most modern APIs, spaces are represented as %20. Decoders of form data interpret + as a space, so a literal plus sign should be encoded as %2B.
Double encoding, or encoding an already-encoded string, results in %2520 instead of %20. To avoid this issue, always encode raw values only once and decode them once to prevent changes in meaning and potential security vulnerabilities. Use your HTTP client or URL builder to handle encoding when possible, rather than manually concatenating strings.
If a link malfunctions, you can use an encoder/decoder tool to see the raw text and debug the problem locally, especially if the URL contains sensitive information. For further reading, you can visit ilovekit.app.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.