URL Encoding Explained: Why Special Characters Get Percent-Encoded
Understand why URLs need encoding, the difference between reserved and unreserved characters, and when to use encodeURIComponent versus encodeURI.
Ever noticed a space turn into %20 or an ampersand become %26 in a link? That is URL encoding, also called percent-encoding, and it is what keeps web addresses valid and unambiguous when they contain special characters.
Why URLs Need Encoding
URLs may only contain a limited set of ASCII characters. Some characters have special meaning, such as ? starting a query string, & separating parameters, and # marking a fragment. If your data contains these characters, they must be encoded so they are treated as data rather than structure.
Reserved vs Unreserved Characters
- Unreserved characters (letters, digits, and - _ . ~) are always safe and never need encoding.
- Reserved characters (such as / ? : @ & = + # ) have special meaning and must be encoded when used as literal data.
- Everything else, including spaces and most symbols, is percent-encoded as a % followed by two hexadecimal digits.
encodeURIComponent vs encodeURI
JavaScript offers two functions, and choosing correctly matters. Use encodeURIComponent for individual values (like a single query parameter) and encodeURI for a complete URL you do not want to break apart.
// Encoding a single query value
encodeURIComponent('name=John & Co');
// 'name%3DJohn%20%26%20Co'
// Encoding a whole URL (keeps / ? & intact)
encodeURI('https://x.com/search?q=hello world');
// 'https://x.com/search?q=hello%20world'Rule of thumb: encode each query parameter value with encodeURIComponent, then assemble the URL. Encoding the whole thing at once often leaves reserved characters unescaped.
The URL Encoder / Decoder lets you encode or decode any string instantly, which is invaluable when debugging query strings, redirects, and API requests.