Uniform Resource Identifiers (URIs) are constrained to a restricted subset of the US-ASCII character set. To safely transmit foreign alphabets, emojis, and special punctuation across the internet, systems rely on Percent-Encoding.
1. Why URLs Require Percent-Encoding
Specified by RFC 3986, percent-encoding replaces illegal or ambiguous byte values with a percent sign (%) followed by two hexadecimal digits representing the character’s ASCII / UTF-8 byte value (e.g. Space = %20).
2. Reserved vs Unreserved Characters
- Unreserved:
A-Z,a-z,0-9,-,_,.,~(never encoded). - Reserved (Delimiters):
:,/,?,#,[,],@,!,$,&,',(,),*,+,,,;,=.
3. encodeURI vs encodeURIComponent
Use encodeURI when you have a complete URL string and want to preserve the protocol (https://) and path slashes (/). Use encodeURIComponent when encoding an isolated query parameter value (such as a search query containing & or =).
4. The %20 vs Plus (+) Space Dilemma
RFC 3986 specifies %20 for spaces everywhere in a URI. The + character for spaces originated in the older HTML form submission specification (application/x-www-form-urlencoded) and is typically accepted only inside URL query parameters.