URL Encoding 101: Special Characters and Encoding Rules
What is URL Encoding?
URL encoding (percent-encoding) converts characters into a format that can be safely transmitted over the internet. URLs can only contain ASCII characters, so any character outside that set must be encoded.
The encoding works by replacing the character with a % followed by two hexadecimal digits representing the byte value. For example, a space character becomes %20.
// Space = %20
https://whetkit.me/tools/url%20encoder
// Ampersand = %26
search?q=hello%26world
// Hash = %23
page%23section1
Common Encoded Characters
| Character | Encoding | Name | When to Encode |
|---|---|---|---|
| %20 | Space | Always — URLs cannot contain literal spaces |
& | %26 | Ampersand | In query values (it's a parameter separator) |
= | %3D | Equals | In query values (it separates key from value) |
# | %23 | Hash / Pound | Always — marks the fragment identifier |
? | %3F | Question Mark | In query values (it starts the query string) |
/ | %2F | Forward Slash | In path segments or query values |
+ | %2B | Plus | In query values (some forms use + for space) |
% | %25 | Percent | Always — to avoid being interpreted as encoding |
encodeURI vs encodeURIComponent
JavaScript provides two encoding functions that serve different purposes. Confusing them is a common source of bugs.
encodeURI
Encodes a full URL. It does not encode characters that are valid URL syntax: : / ? # [ ] @ ! $ & ' ( ) * + , ; =
encodeURI("https://whetkit.me/tools/formatter?name=John Doe")
// "https://whetkit.me/tools/formatter?name=John%20Doe"
// Note: / ? = & are NOT encoded
encodeURIComponent
Encodes a URL component (like a query parameter value). It encodes everything except A-Z a-z 0-9 - _ . ! ~ * ' ( )
encodeURIComponent("https://whetkit.me/path?q=hello world")
// "https%3A%2F%2Fwhetkit.me%2Fpath%3Fq%3Dhello%20world"
// Note: : / ? = are ALL encoded
Rule of thumb: Use encodeURI when you have a complete URL. Use encodeURIComponent when encoding individual values to insert into a URL. Always encode query parameter values with encodeURIComponent.
Query String Encoding
Query strings are the most common place where encoding matters. A single unencoded character can break your entire request.
// Building a query string correctly
const params = new URLSearchParams();
params.append("search", "hello world & goodbye"); // spaces and &
params.append("page", "1");
params.append("sort", "date asc");
const url = `/search?${params.toString()}`;
// /search?search=hello+world+%26+goodbye&page=1&sort=date+asc
Always use URLSearchParams or encodeURIComponent when building query strings manually. Never concatenate raw user input into a URL.
Need to encode or decode URLs quickly?
Try URL Encoder/Decoder