Which encoding to use
Building ?q= from user input? Encode just the value with Component (encodeURIComponent). Cleaning up a full URL that has spaces or accents in it? Use Full URL (encodeURI), which keeps / ? & = # intact. Sending a form body or reading one? Form turns spaces into +, like URLSearchParams does.
| Character | Component | Full URL | Form |
|---|---|---|---|
space | %20 | %20 | + (forms) |
& | %26 | & | %26 |
= | %3D | = | %3D |
? | %3F | ? | %3F |
/ | %2F | / | %2F |
# | %23 | # | %23 |
+ | %2B | + | %2B |
% | %25 | %25 | %25 |
é | %C3%A9 | %C3%A9 | %C3%A9 |
✓ | %E2%9C%93 | %E2%9C%93 | %E2%9C%93 |
In code
// JavaScript
const url = `https://api.example.com/search?q=${encodeURIComponent(query)}`;
new URLSearchParams({ q: 'café & crêpes' }).toString(); // q=caf%C3%A9+%26+cr%C3%AApes
# Python
from urllib.parse import quote, unquote, urlencode
quote('café & crêpes', safe='') # caf%C3%A9%20%26%20cr%C3%AApes
urlencode({'q': 'café & crêpes'}) # q=caf%C3%A9+%26+cr%C3%AApesThe rules come from RFC 3986, which lists the characters that may appear unescaped in a URI; everything else is written as a percent sign plus two hex digits per UTF-8 byte.