URL Encoding & Decoding: Definitive Guide
Percent-encoding keeps URLs and query strings safe. Here’s when to encode, when to decode, and how to avoid common pitfalls.
We see them every day: those strange %20 and %3F sequences cluttering our browser address bars. But what exactly is URL encoding, and why do URLs need it?
The ASCII Limitation
The internet was born in an era where US-ASCII was the standard. URLs were designed to only support a specific subset of characters: alphanumerics and a handful of special symbols like -, _, ., and ~.
But the world is rich with diverse languages, emojis, and complex data. How do you put a space, a Cyrillic letter, or a query parameter containing & into a URL without breaking it? Enter Percent-Encoding.
How Percent-Encoding Works
Percent-encoding is a mechanism for encoding information in a Uniform Resource Identifier (URI). Characters are replaced by a % followed by their two-digit hexadecimal value.
| Character | Encoded Value | Reason |
|---|---|---|
| Space | %20 | Unsafe in URLs |
| / | %2F | Path separator |
| ? | %3F | Query string start |
| & | %26 | Parameter separator |
Common Pitfalls
Double Encoding
A frequent bug occurs when a string is encoded twice. Hello World becomes Hello%20World, which if encoded again becomes Hello%2520World (since % becomes %25). Decoding this once leaves you with the still-encoded string, leading to confusing bugs.
Encoding the Entire URL
You should generally only encode the values of query parameters, not the entire URL string. Encoding the :// or the ? will break the browser's ability to parse the protocol and path.
Real-World Examples
Example 1: Search Query with Special Characters
Imagine you're building a search feature and a user searches for "C++ tutorial". The plus signs need to be encoded:
Original: C++ tutorial
Encoded: C%2B%2B+tutorial
URL: https://example.com/search?q=C%2B%2B+tutorialExample 2: International Characters
URLs with non-ASCII characters must be encoded. For example, "café" becomes:
Original: café
Encoded: caf%C3%A9
URL: https://example.com/place?name=caf%C3%A9Example 3: Query Parameters with Multiple Values
When building complex query strings, each parameter value must be encoded separately:
Original: category=electronics&search=phone & charger
Encoded: category=electronics&search=phone%20%26%20charger
URL: https://shop.com/products?category=electronics&search=phone%20%26%20chargerEncoding in Different Languages
Most programming languages provide built-in functions for URL encoding:
// JavaScript
encodeURIComponent("hello world") // "hello%20world"
decodeURIComponent("hello%20world") // "hello world"
# Python
from urllib.parse import quote, unquote
quote("hello world") # "hello%20world"
unquote("hello%20world") # "hello world"
quote("a/b") # "a/b" (safe="/" by default. Use safe="" to encode it)
// PHP
urlencode("hello world") // "hello+world"
urldecode("hello+world") // "hello world"Reserved, Unreserved, and What Actually Gets Encoded
RFC 3986 splits ASCII characters into three groups. Unreserved characters (letters, digits, -, ., _, ~) never need encoding. Reserved characters act as delimiters: the general delimiters are : / ? # [ ] @, and the sub-delimiters are ! $ & ' ( ) * + , ; =. Everything else, including spaces, quotes, and all non-ASCII characters, must be encoded.
The key rule is that a reserved character is only safe to leave alone when you want it to act as a delimiter. A / in a path separates segments, but a / inside a filename that belongs in one segment must become %2F. The same character can therefore need different treatment depending on which URL component you are filling in.
How Non-ASCII Text Is Encoded
For non-ASCII characters, RFC 3986 says the text should first be encoded as UTF-8 and each byte then percent-encoded, and the WHATWG URL Standard (which browsers and the URL class implement) does the same. That is why é (two bytes in UTF-8) becomes %C3%A9, € becomes %E2%82%AC, and an emoji such as 😀 becomes four encoded bytes:
encodeURIComponent("café 😀")
// "caf%C3%A9%20%F0%9F%98%80"
decodeURIComponent("%e2%82%ac")
// "€" (hex digits are case-insensitive when decoding)RFC 3986 says producers should use uppercase hex digits (%C3, not %c3) but treats the two cases as equivalent, so decoders must accept both. Older systems sometimes used Latin-1 or other legacy charsets for percent-encoded bytes. If you see caf%E9 instead of caf%C3%A9, you are looking at a Latin-1 encoded value, which a UTF-8 decoder will reject or misread. (The deprecated JavaScript escape() function also produces nonstandard output such as %u20AC, so avoid it.)
encodeURI vs encodeURIComponent
JavaScript ships two encoders, and picking the wrong one is the most common encoding bug. encodeURI is meant for a complete URL, so it leaves delimiters like :, /, ?, #, &, = and + alone. encodeURIComponent is meant for a single value, so it encodes all of them. Here is what each one returns for the same strings:
encodeURIComponent("a b&c=d/e?f#g+h~i'(j)!*")
// "a%20b%26c%3Dd%2Fe%3Ff%23g%2Bh~i'(j)!*"
encodeURI("a&b=c#d+e")
// "a&b=c#d+e" (nothing changed: all are delimiters)
encodeURI("https://example.com/a b?q=x y&z=1#frag é")
// "https://example.com/a%20b?q=x%20y&z=1#frag%20%C3%A9"| Use case | Use | Why |
|---|---|---|
| A query parameter value | encodeURIComponent | Must escape &, =, #, + |
| One path segment | encodeURIComponent | Must escape / and ? |
| A whole URL with spaces or accents | encodeURI | Keeps the structure intact |
| Building a URL from parts | URL + URLSearchParams | Encodes per component for you |
Neither function encodes ', (, ), ! or *, which are legal sub-delimiters. That is fine for URLs, but if you embed an encoded value into HTML attributes or shell commands, escape for that context separately: percent-encoding is not a general-purpose sanitizer.
Plus Sign or %20 for Spaces?
Both appear in the wild because they come from two different specifications. RFC 3986 percent-encoding has no special case for spaces: a space is %20. The application/x-www-form-urlencoded format, used by HTML form submissions and implemented by URLSearchParams, writes a space as + and therefore must write a literal plus as %2B. The consequence is that the meaning of + depends on where it appears:
encodeURIComponent("a b") // "a%20b"
new URLSearchParams({ q: "a b" }).toString() // "q=a+b"
new URLSearchParams("q=a+b%2Bc").get("q") // "a b+c"
decodeURIComponent("a+b%2Bc") // "a+b+c" (+ is NOT turned into a space)
new URL("https://example.com/a+b").pathname // "/a+b" (literal plus in a path)The practical rule: never use decodeURIComponent alone to read a form-style query string, since it will leave + characters in place. Either parse with URLSearchParams, or replace + with a space before decoding. When you encode a value and are unsure which parser will read it, %20 is accepted by both, whereas + is only a space in form-style queries.
Decoding Safely
Decoding fails when the input contains a % that is not followed by two hex digits, or when the decoded bytes are not valid UTF-8. In JavaScript both cases throw:
decodeURIComponent("100%")
// URIError: URI malformed
decodeURIComponent("%E0%A4%A")
// URIError: URI malformed
function safeDecode(value) {
try {
return decodeURIComponent(value);
} catch {
return value; // keep the raw text if it is not valid encoding
}
}
safeDecode("100%") // "100%"
safeDecode("caf%C3%A9") // "café"URLSearchParams is more forgiving: it leaves invalid sequences as they are, so new URLSearchParams("q=100%").get("q") returns "100%" rather than throwing. Also note that encodeURIComponent can throw, for example on a lone UTF-16 surrogate such as "\uD800", which is not valid Unicode text.
Debugging Double Encoding
If you see %25 anywhere in a URL, suspect double encoding: %25 is the encoded form of % itself. A quick check is to decode once and see whether the result still contains %XX sequences:
encodeURIComponent(encodeURIComponent("Hello World"))
// "Hello%2520World"
decodeURIComponent("Hello%2520World")
// "Hello%20World" <- still encoded after one passThe fix is almost never to decode twice. Find the layer that encodes twice, typically a manual encodeURIComponent followed by an HTTP client, router, or URLSearchParams that encodes again. Decide on one layer that owns encoding and pass raw values to it. Paste suspicious strings into the URL Decoder and decode step by step to see which layer added the extra %25.
Security Considerations
- Injection through unencoded values: an unencoded
&or#in user input can add or truncate parameters. If a value likex&admin=trueis concatenated into a URL, the server sees an extraadminparameter. Encode every value. - Validate after decoding, exactly once:
%2e%2e%2fdecodes to../, so a check on the raw string sees nothing suspicious. Decoding twice is just as dangerous: a filter that rejects../after one decode can miss%252e%252e%252f, which becomes../after a second decode somewhere downstream. - Keep encoding and escaping separate: percent-encoding makes a value safe for a URL only. Values rendered into HTML still need HTML escaping.
For deeper coverage of validating incoming links, see URL Validation Best Practices, and for how each component is laid out, URL Anatomy.
Best Practices
- Encode values, not whole URLs: apply
encodeURIComponent(or letURLSearchParamsdo it) to each query value and path segment, once, in one layer. - Reserve
encodeURIfor cleaning up a complete URL that already has its structure right but contains spaces or accents. - Treat decoding as fallible: wrap
decodeURIComponentintry/catch, as shown above.
Tools of the Trade
When a URL is broken and you cannot tell which layer mangled it, paste it into the URL Encoder or URL Decoder. Encoding or decoding a suspect string one step at a time is often enough to spot a stray %25 or an unencoded &.
Frequently Asked Questions
Why does a space become %20 in some URLs and + in others?
%20 is standard percent-encoding and works anywhere in a URL. + is a space only in application/x-www-form-urlencoded data such as HTML form submissions and query strings parsed with URLSearchParams. In a path, + is just a plus sign.
What is the difference between encodeURI and encodeURIComponent?
encodeURI keeps URL delimiters such as /, ?, &, and # so a full URL stays valid. encodeURIComponent encodes them, which is what you want for a single path segment or query value.
What does %25 mean in a URL?
It is the encoded form of the percent sign. Seeing it before hex digits, as in %2520, usually means the value was encoded twice: the original %20 had its % encoded again.
Why does decodeURIComponent throw "URI malformed"?
The string contains a % that is not followed by two hex digits, or percent-encoded bytes that do not form valid UTF-8. Wrap the call in try/catch and fall back to the raw value, or parse with URLSearchParams, which does not throw on these inputs.
Written by Kashyap Thakar
Spotted a mistake? Let me know
Try these tools
Use these tools alongside this guide