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

CharacterEncodingNameWhen to Encode
%20SpaceAlways — URLs cannot contain literal spaces
&%26AmpersandIn query values (it's a parameter separator)
=%3DEqualsIn query values (it separates key from value)
#%23Hash / PoundAlways — marks the fragment identifier
?%3FQuestion MarkIn query values (it starts the query string)
/%2FForward SlashIn path segments or query values
+%2BPlusIn query values (some forms use + for space)
%%25PercentAlways — 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