How to URL-Encode Strings for Query Parameters
URL Encoding
When to URL-Encode
Encode text before placing it in query strings, redirect URLs, or path segments where spaces, ampersands, unicode, or reserved characters would break the URL structure.
Real-World Examples
hello world → hello%20world
price=$10&tax=5% → encode the value portion before building the query string
user@example.com → user%40example.com
Common Mistakes
- Encoding an entire URL including scheme and domain (encode values, not the full URL)
- Double-encoding values that APIs already encode
- Using
+for spaces in paths — paths typically use%20
Edge Cases
encodeURIvsencodeURIComponenttreat reserved characters differently in JavaScript- Unicode characters encode as UTF-8 byte sequences (often multiple %XX groups)
- Empty values are valid:
?q=
Security Considerations
Encoding does not sanitize malicious input. Always validate decoded values server-side, especially in redirect URLs where open redirects are a common vulnerability.
Developer Tips
- JavaScript:
encodeURIComponent()for query values - Python:
urllib.parse.quote() - Build query strings with URLSearchParams instead of manual concatenation
Frequently asked questions
Should I encode the entire URL?
Usually no. Encode individual query values or path segments that contain user input, not the scheme or hostname.
What is the difference between encodeURI and encodeURIComponent?
encodeURI is for full URIs and preserves characters like / and ?. encodeURIComponent encodes nearly all special characters and is meant for query parameter values.
Why is my space encoded as %20 instead of +?
Both are valid in query strings. encodeURIComponent produces %20. Form submissions historically used + for spaces.