URLs can only contain a limited set of characters. Everything else, including spaces, accented letters, emoji and characters with a special meaning like & or ? inside a value, has to be percent-encoded: written as % followed by the byte's value in hex. A space becomes %20, and é, which is two bytes in UTF-8, becomes %C3%A9.
Original red shoes & more?
Encoded red%20shoes%20%26%20more%3FWhich characters need encoding
- Never encoded: letters, digits and
- _ . ~. - Reserved, with a meaning in URLs:
: / ? # [ ] @ ! $ & ' ( ) * + , ; =. Leave them as they are when they structure the URL, and encode them when they're part of a value. A search forR&Dmust be sent asq=R%26D, or the server sees a new parameter. - Everything else, such as spaces, quotes,
%itself and any non-ASCII character, is always encoded.
%20 or +?
Both mean “space”, but in different places. %20 is valid everywhere in a URL. + means a space only in query strings encoded the way HTML forms send them (application/x-www-form-urlencoded); in a path, + is just a plus sign. When decoding a query string, check which convention the sender used, or a+b won't turn back into a b.
In JavaScript
JavaScript has two built-in functions, and picking the wrong one is the most common URL bug:
encodeURIComponent("a b&c=d/é?"); // "a%20b%26c%3Dd%2F%C3%A9%3F" (for a single value)
encodeURI("https://ex.com/a b?q=é&x=1#top");
// "https://ex.com/a%20b?q=%C3%A9&x=1#top" (for a whole URL; keeps : / ? & = #)
// Building a query string: let URLSearchParams do the encoding
new URLSearchParams({ q: "red shoes & more", lang: "fr" }).toString();
// "q=red+shoes+%26+more&lang=fr"
decodeURIComponent("a+b%20c"); // "a+b c": + is not decoded
new URLSearchParams("q=a+b%20c").get("q"); // "a b c": form conventionUse encodeURIComponent for anything you insert into a URL (a parameter value or a path segment), and encodeURI only to clean up a complete URL that may contain spaces or non-ASCII characters.
In Python
from urllib.parse import quote, quote_plus, urlencode, unquote_plus
quote("a b&c=d/é?") # "a%20b%26c%3Dd/%C3%A9%3F" (keeps / by default)
quote("a b/c", safe="") # "a%20b%2Fc" (encode / too)
quote_plus("a b&c") # "a+b%26c" (spaces as +, for form data)
urlencode({"q": "red shoes & more", "lang": "fr"}) # "q=red+shoes+%26+more&lang=fr"
unquote_plus("a+b%20c") # "a b c"Encode and decode online
The URL Encoder/Decoder encodes and decodes as you type. Choose query-value, full-URL or form encoding, convert many lines at once, and paste a full URL to see its parts and every query parameter decoded. If decoding fails, it tells you the position of the bad % sequence. It runs entirely in your browser.
URL encoding only makes text safe inside a URL. To embed binary data or a whole file as text, use Base64 instead.