The Problem URLs Had to Solve
When Tim Berners-Lee designed the URL (Uniform Resource Locator) in 1994, he faced a fundamental constraint: URLs could only contain characters from the ASCII character set — the 128 characters that were universally supported across all computers and network protocols at the time.
But web addresses needed to carry real-world data: search queries, usernames, file paths, and form values — content that naturally includes spaces, accented characters, emoji, and punctuation. Worse, several ASCII characters like ?, &, #, and / already had structural meaning in a URL. They couldn't be used as data values without creating ambiguity.
URL encoding was the solution. It provides a safe, reversible way to represent any character inside a URL by replacing it with an escape sequence.
How Percent-Encoding Works
The mechanism is straightforward. Each unsafe character is replaced with a % sign followed by the two-digit uppercase hexadecimal value of that character's UTF-8 byte.
The space character (ASCII 32, hex 0x20) becomes %20. The ampersand (ASCII 38, hex 0x26) becomes %26. Characters that are unreserved — letters A–Z, digits 0–9, and - _ . ~ — are left exactly as they are.
For characters outside ASCII (like accented letters or emoji), the character is first converted to its UTF-8 byte sequence, and each byte is separately percent-encoded. The emoji 🚀, for example, encodes to %F0%9F%9A%80.
Reserved vs Unreserved Characters
RFC 3986 divides URL characters into two groups:
Unreserved — never encoded
A–Z a–z 0–9 - _ . ~These are safe in any part of a URL.
Reserved — encode when used as data
: / ? # [ ] @ ! $ & ' ( ) * + , ; =These have structural meaning and must be encoded when used as values.
URL Encoding in JavaScript
JavaScript has two built-in functions. Choosing the wrong one is a common mistake:
encodeURI(url)
Use when encoding a complete URL. Leaves reserved characters like /, ?, & intact because they're part of the URL structure.
encodeURI("https://example.com/path?q=hello world") → "https://example.com/path?q=hello%20world"encodeURIComponent(value)
Use when encoding a query parameter value or any URL component. Encodes reserved characters too, so they can't be misread as URL structure.
encodeURIComponent("hello & world?") → "hello%20%26%20world%3F"Rule of thumb: When in doubt, use encodeURIComponent() for user-provided values in query strings.
Common Pitfalls
Try the URL Encoder
Encode or decode any text instantly — 100% client-side, no data leaves your browser.