/tutorials/percent-encoding-explained
Percent Encoding Explained
Why URLs escape spaces and special characters as codes like %20, and how to tell percent encoding apart from other kinds of encoding.
5 min read
Run URL Encoder/DecoderRelated tools
Why URLs cannot just contain any character
A URL is restricted to a limited set of characters by its own specification, largely because certain characters already have special meaning within a URL itself, like / separating path segments or ? starting a query string. Spaces, non-ASCII characters and several punctuation marks either are not allowed at all or would be ambiguous if included literally, so they need to be represented a different way.
How percent encoding actually represents them
Percent encoding replaces a character with a percent sign followed by its byte value in hexadecimal. A space becomes %20, an ampersand becomes %26, and a non-ASCII character is first converted to its UTF-8 byte representation and then each of those bytes is percent encoded in turn, which is why a single accented letter can turn into several %XX codes in a row rather than just one.
Encoding a whole URL versus one piece of it
Encoding an entire URL and encoding a single value that will be placed inside one are different operations. Encoding a full URL should leave structural characters like / and ? alone, since encoding those would break the URL's own structure. Encoding a single query parameter value, on the other hand, should escape those same characters, since a literal & or = inside a value would otherwise be misread as a new parameter starting.
Where this actually comes up
This matters most when building a URL by hand that includes user-provided text, like a search query or a file name with spaces in it, or when reading a URL you have copied from somewhere and it is full of unfamiliar %XX sequences you want to read in plain text.
Trying it yourself
URL Encoder/Decoder converts text to and from percent encoding using the same functions built into every modern browser. Try encoding a sentence with spaces and an ampersand in it, and notice exactly which characters change and which do not.
Related tutorials
