URL Encoding: What %20 Means and When to Use encodeURIComponent
URL encoding swaps special characters for %HH. Learn %20 vs +, encodeURI vs encodeURIComponent, and how to build query strings without breaking the URL.
A search feature was breaking intermittently. After half an hour of debugging, the problem was obvious: someone was putting a parameter value straight into the query string without encoding it, and the value contained an &. The server received two parameters where it should have received one. The fix was one line of code that should have been there from the start.
URL encoding — technically called percent-encoding — is the mechanism that replaces problematic characters with %HH sequences so they fit inside a URL without breaking its structure. The syntax lives in RFC 3986, from 2005. This post explains what %20 means, why a space sometimes becomes +, the real difference between encodeURI and encodeURIComponent (with each function's output actually tested, not recited from memory), and where %2F bites you on the server.
Why URLs need encoding
A URL has structure. RFC 3986 splits characters into three groups:
- Unreserved: letters
A-Zanda-z, digits0-9, and the symbols-,.,_,~. They can appear literally anywhere. - Reserved: the general delimiters
: / ? # [ ] @and the sub-delimiters! $ & ' ( ) * + , ; =. They carry structural meaning:?separates the path from the query string,&separates parameters,=separates key from value. - Everything else: spaces, accented letters, anything outside ASCII, control characters. These always have to be encoded.
When a reserved character shows up as part of a value — an & in a company name, a / in an identifier — the parser cannot tell data from delimiter. Encoding removes the ambiguity.
How percent-encoding works (and what %20 means)
Each byte that needs encoding becomes % followed by two hex digits with the byte's value. A space is byte 0x20, so it becomes %20. That is all %20 in the address bar means.
| Character | UTF-8 byte(s) | Encoded |
|---|---|---|
| space | 0x20 |
%20 |
& |
0x26 |
%26 |
= |
0x3D |
%3D |
+ |
0x2B |
%2B |
/ |
0x2F |
%2F |
ã |
0xC3 0xA3 |
%C3%A3 |
é |
0xC3 0xA9 |
%C3%A9 |
Notice that ã and é each produce two %HH. Encoding operates on bytes, not characters: the text is first converted to UTF-8, then each byte outside the allowed set becomes %HH. That is why café becomes caf%C3%A9. If the server decodes those bytes as Latin-1, you get the classic café — the same problem described in UTF-8 encoding problems.
Space as +: only in the query string
There is a second convention that still causes bugs. The application/x-www-form-urlencoded format — what browsers use to submit HTML forms, and what URLSearchParams produces — represents a space as +. RFC 3986 uses %20.
application/x-www-form-urlencoded
name=Rafael+Duarte&city=S%C3%A3o+Paulo
RFC 3986 percent-encoding
name=Rafael%20Duarte&city=S%C3%A3o%20Paulo
Two rules keep you safe. First: + as a space only applies in the query string or a form body. In the path, /a+b literally means "a+b". Second: the decoder must know which convention it received. decodeURIComponent('a+b%20c') returns a+b c (the + stays), while new URLSearchParams('q=a+b%20c').get('q') returns a b c.
PHP has the same split: urlencode() uses + for spaces (form encoding) and rawurlencode() uses %20 (RFC 3986). Likewise, urldecode('a+b%20c') returns a b c and rawurldecode('a+b%20c') returns a+b c. For path segments, rawurlencode() is the right choice.
encodeURI vs encodeURIComponent: what each one encodes
This is the part tutorials most often get wrong, so I ran each character through JavaScript's three APIs (Node 24, which follows the same standard as browsers):
| Character | encodeURI |
encodeURIComponent |
URLSearchParams |
|---|---|---|---|
| space | %20 |
%20 |
+ |
& = + $ , ; : @ |
left as is | %26 %3D %2B %24 %2C %3B %3A %40 |
encoded |
/ ? # |
left as is | %2F %3F %23 |
encoded |
[ ] |
%5B %5D |
%5B %5D |
%5B %5D |
! ' ( ) |
left as is | left as is | %21 %27 %28 %29 |
* |
left as is | left as is | left as is |
~ |
left as is | left as is | %7E |
é |
%C3%A9 |
%C3%A9 |
%C3%A9 |
Three things the table settles:
encodeURIComponentdoes not encode! ' ( ) *. MDN lists the characters it preserves:A–Z a–z 0–9 - _ . ! ~ * ' ( ). So a'passes through raw — relevant if the value ends up inside an HTML attribute or a system that follows RFC 3986 strictly.encodeURIdoes encode[and]. It preserves the other reserved characters, but brackets come out as%5B%5D.URLSearchParamsfollows a different table: it encodes! ' ( ) ~, leaves*alone and turns spaces into+, because it implements the form encoding defined in the WHATWG URL Standard.
If you need strict RFC 3986, MDN publishes this function, which I tested:
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
encodeURIComponent("it's (ok)*!"); // "it's%20(ok)*!"
encodeRFC3986URIComponent("it's (ok)*!"); // "it%27s%20%28ok%29%2A%21"
The practical rule stays simple: encodeURI is for a full URL that already has structure; encodeURIComponent is for a value that goes inside one. The classic mistake is swapping them:
// WRONG: encodeURI doesn't encode & → the query string breaks
`https://api.example.com/search?q=${encodeURI('café & cake')}`
// https://api.example.com/search?q=caf%C3%A9%20&%20cake
// the server reads q="café " plus a second parameter " cake"
// RIGHT: & becomes %26
`https://api.example.com/search?q=${encodeURIComponent('café & cake')}`
// https://api.example.com/search?q=caf%C3%A9%20%26%20cake
The reverse breaks too: encodeURIComponent('https://a.com/x?y=1') returns https%3A%2F%2Fa.com%2Fx%3Fy%3D1, which is no longer a navigable URL. To check a specific value without opening the console, the URL encoder shows the result instantly.
Build query strings with URL and URLSearchParams
String concatenation is where the bugs are born. The URL API does the encoding right on its own:
function buildSearchUrl(base, params) {
const url = new URL(base);
Object.entries(params).forEach(([key, value]) => {
url.searchParams.set(key, String(value));
});
return url.toString();
}
buildSearchUrl('https://api.example.com/search', {
q: 'node.js & express',
page: 2,
tags: 'backend,api',
author: 'Rafael Duarte',
});
// https://api.example.com/search?q=node.js+%26+express&page=2&tags=backend%2Capi&author=Rafael+Duarte
The result uses + for spaces. For web APIs that is expected: frameworks decode query strings as form encoding. Filters, pagination and sorting in the query are the typical case — the post on REST API best practices covers how to design those parameters.
In PHP, http_build_query() plays the same role (tested on PHP 8.2):
echo http_build_query([
'q' => 'node.js & express',
'page' => 2,
'author' => 'Rafael Duarte',
]);
// q=node.js+%26+express&page=2&author=Rafael+Duarte
The most common mistakes
Not encoding a parameter value. The bug from the start of this post. Every dynamic value in a query string goes through URLSearchParams or encodeURIComponent.
Encoding twice. %26 encoded again becomes %2526, because % turns into %25. The server decodes once and receives a literal %26 instead of &. It happens when two layers of code (a helper and an HTTP client, say) both encode the same value without agreeing on who does it.
Assuming %2F turns back into a harmless /. It depends on the server, and I tested two in Docker. On Apache 2.4 with the default configuration, GET /a%2Fb returns 404: the AllowEncodedSlashes directive defaults to Off and refuses encoded slashes in the path. On Nginx 1.31, the same request returned 200 serving the file /a/b — that is, %2F was treated as a segment separator. If your identifier can contain /, keep it out of the path; send it in the query string or change the id format.
Decoding with a regex. decodeURIComponent('%E0%A4%A') throws URIError: URI malformed. The standard functions validate multibyte sequences; a hand-rolled %HH replace validates nothing.
URL encoding vs Base64
They solve different problems. Percent-encoding makes text fit inside a URL; output grows up to 3x for each encoded byte. Base64 represents arbitrary binary data as ASCII text and has nothing specifically to do with URLs; the post What Is Base64? covers that mechanism in detail.
The confusion comes from seeing them together. Standard Base64 uses +, / and =, all reserved; if a Base64 value goes into a query string, it must be percent-encoded, or the + turns into a space on the server. That is why the Base64URL variant (with - and _) exists, used in the tokens described in how JWT works.
Frequently asked questions
Why does my URL have %20 in some places and + in others?
They are two conventions. %20 is RFC 3986 percent-encoding and is valid anywhere in a URL. + for space comes from the application/x-www-form-urlencoded format, used by HTML forms and URLSearchParams, and only applies in the query string or a form body. Modern servers accept both in the query; in the path, only %20 means a space.
Does encodeURIComponent encode /? Can I use %2F in a path segment?
It does: / becomes %2F. But what the server does with it varies. Apache, by default, answers 404 for paths containing %2F; Nginx, in my test, treated %2F as a regular slash. If a value can contain /, send it in the query string rather than the path.
How do I decode an encoded URL?
In JavaScript, decodeURIComponent() reverses encodeURIComponent and decodeURI() reverses encodeURI; for query strings, URLSearchParams hands you decoded values, including treating + as a space. In PHP, urldecode() and rawurldecode(). To look at a value quickly, the URL decoder does it without code.
Is URL encoding the same as HTML encoding?
No. HTML encoding replaces <, >, & and " with entities (<, >, &, ") so text doesn't break the HTML document. URL encoding replaces bytes with %HH so text doesn't break the URL. Sometimes you need both: a URL inside an href needs percent-encoded values and the & between parameters written as & in the HTML.
The rule that removes most of the bugs
URL encoding is simple in concept — every byte becomes %HH — and treacherous in the conventions piled on top: + for space only in the query, encodeURIComponent letting ! ' ( ) * through, URLSearchParams with its own table, servers that disagree about %2F. Build query strings with URL/URLSearchParams in JavaScript and http_build_query() in PHP; reach for encodeURIComponent by hand only for a single value; and never concatenate dynamic data into a URL without going through one of those functions.
- 01 Does the PageSpeed Score Affect SEO? 100/100 and Failing Google doesn't rank on PageSpeed's 0 to 100 score but on Core Web Vitals from real users. Here's why a site scores 100/100 and still fails in the field.
- 02 Unit test vs integration test: the difference in practice The difference between unit and integration tests with API and database examples: what each one catches, what it costs, and when to use each in your project.