Introduction
URL encoding (also called percent encoding) is essential for web development. Every time you submit a form, send API parameters, or include special characters in a URL, encoding ensures your data arrives correctly. Without proper encoding, URLs break, forms fail, and API calls return errors. This guide explains everything you need to know about URL encoding.
What is URL Encoding?
URL encoding converts special characters into a format that can be safely transmitted over the internet. URLs can only contain certain characters from the ASCII character set. Any character outside this set must be encoded as %XX where XX is the hexadecimal ASCII value.
Characters That Need Encoding
Why URL Encoding Matters
URLs have a specific structure defined by RFC 3986. Certain characters serve as delimiters that separate different parts of a URL:
- ? separates the path from query parameters
- & separates multiple parameters
- = separates parameter names from values
- / separates path segments
- # marks the fragment identifier
If you use these characters as data rather than delimiters, they must be encoded. Otherwise, browsers and servers misinterpret the URL structure, causing broken links and failed requests.
Common Use Cases
Query Parameters
When sending search queries, user input, or filter values, encode them to prevent parameter injection and ensure correct transmission.
search=hello%20world&filter=price%3E100API Requests
REST APIs expect encoded parameters. Unencoded special characters cause 400 errors or unexpected behavior.
GET /api/users?name=John%20DoePath Segments
Dynamic URLs with user-generated content (slugs, filenames) need encoding to prevent path traversal and maintain valid URLs.
/files/report%202024.pdfForm Submissions
HTML forms automatically encode data. Understanding encoding helps debug form issues and create custom submission handlers.
FormData automatically encodesEncoding vs Decoding
The Two-Way Process
- Encoding (urlencode)Converts special characters to %XX format before sending in URLs. Use this when constructing URLs with dynamic data.
- Decoding (urldecode)Converts %XX sequences back to original characters. Use this when receiving and processing URL parameters.
Most programming languages provide built-in functions: JavaScript has encodeURIComponent()and decodeURIComponent(), Python has urllib.parse.quote()and unquote().
Quick Tips
- Always encode query parameter values, even if they look safe
- Spaces can be encoded as %20 or + - %20 is more universal
- Double-encoding causes bugs: %20 becomes %2520
- URLs have a max length (2083 chars in some browsers) - encoding increases length
- Reserved characters: ! * ' ( ) ; : @ & = + $ , / ? % # [ ]