URL Encoding: What It Is and Why It Matters
Understand percent-encoding in URLs, when to encode/decode, and common pitfalls when building web applications.
You've probably seen URLs that look like %20 or %2F and wondered what those mean. That's URL encoding — also called percent-encoding — and it's fundamental to how the web works.
What is URL Encoding?
URLs can only contain a limited set of safe ASCII characters. Spaces, special characters, and non-ASCII characters (like accented letters or Chinese characters) must be encoded before being included in a URL. URL encoding replaces these characters with a % followed by their two-digit hexadecimal ASCII code.
Common Encoded Characters
- Space → %20 (or + in query strings)
- / → %2F
- ? → %3F
- # → %23
- & → %26
- = → %3D
- @ → %40
When to Encode URLs
You need to URL-encode when: building query parameters dynamically, handling user-submitted search terms, working with file names that contain spaces, or passing data through URL parameters.
// JavaScript — encode a query parameter value
const query = "hello world & more";
const encoded = encodeURIComponent(query);
// Result: "hello%20world%20%26%20more"
// Build a URL safely
const url = `https://example.com/search?q=${encodeURIComponent(query)}`;Tip
Use encodeURIComponent() to encode individual parameter values. Use encodeURI() only for full URLs. Never concatenate user input directly into URLs without encoding.
The Difference Between encodeURI and encodeURIComponent
- encodeURI() — encodes a full URL, preserving structural characters like /, ?, &, =
- encodeURIComponent() — encodes a URL component (like a parameter value), encoding ALL special characters
Double Encoding Trap
A common mistake is encoding a string that's already encoded. This turns %20 into %2520 (the % itself gets encoded). Always decode first before re-encoding, or check that a string isn't already encoded.