Web & APIs · 4 min read
URL Encoding Explained (Percent-Encoding)
URLs can only contain a limited set of characters, so anything else — spaces, accents, ampersands used as data — has to be percent-encoded. Getting this wrong is a common source of broken links and subtle bugs.
This guide explains what percent-encoding is and which encoding function to use where.
Try it yourself with the related tool.
Encode or decode a URL →Advertisement
What percent-encoding is
Percent-encoding represents an unsafe character as a % followed by two hex digits of its byte value. A space becomes %20, an ampersand becomes %26. This lets arbitrary text ride safely inside a URL without breaking its structure.
encodeURIComponent vs encodeURI
Use encodeURIComponent for a single value, like a query parameter, because it escapes URL-structural characters such as &, =, ?, and /. Use encodeURI for a whole URL you do not want to break, since it leaves those structural characters intact. Choosing the wrong one either corrupts the URL or leaves data improperly escaped.
Why it prevents bugs
If a query value contains an unencoded & or =, the server cannot tell where one parameter ends and the next begins. Encoding user input before placing it in a URL avoids these parsing errors and a class of injection issues.
Unicode and spaces
Non-ASCII characters are first converted to UTF-8 bytes, then percent-encoded, so accented letters and emoji round-trip correctly. Note that in form submissions a space is sometimes written as + rather than %20; both decode back to a space.
