Why Do Spaces Become %20 in URLs?
If you've ever copied a link that contained a space, you probably noticed that the space was replaced by the characters %20. This is the most common and visible example of URL encoding. But why %20 specifically?
The Rules of URLs
The foundation of the World Wide Web relies on Uniform Resource Locators (URLs). When the web was designed, rules were established regarding what characters could be sent over the network in a URL. The rule was strict: URLs can only be transmitted using a subset of the ASCII character set.
More importantly, literal spaces are completely forbidden in URLs. In HTTP protocols, a space is used to separate the method (like GET), the URL path, and the HTTP version. If a URL contained a space, the server wouldn't know where the URL ended and the next command began.
The Percent-Encoding Solution
To fix this, web standards created percent-encoding. When an unallowable character (like a space) needs to be included in a URL, it is escaped.
The escaping mechanism uses the percent sign (%) followed by a two-digit hexadecimal number that represents the character's value in the ASCII table.
The Math Behind %20
If you look at an ASCII table, every character is assigned a decimal number.
- The letter 'A' is 65.
- The letter 'a' is 97.
- The Space character is 32.
Now, we need to convert that decimal number (32) into a hexadecimal (base-16) number.
In hexadecimal, the number 32 is written as 20. (2 * 16^1 + 0 * 16^0 = 32).
Combine the percent sign with the hex value, and you get %20.
What About the Plus (+) Sign?
You might sometimes see spaces replaced by a plus sign (+) instead of %20. For example: ?q=hello+world.
This is a specific rule that applies only to the query string part of a URL (the part after the ?), specifically when submitting HTML forms with the application/x-www-form-urlencoded content type. However, %20 is always universally valid everywhere in a URL, making it the safer and more standard choice for modern web development.
Test it out yourself! Type any sentence with spaces into our URL Encoder to see the spaces instantly convert to %20.