What is URL Encoding?
URL encoding, also known as percent-encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI). It replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits representing the character's ASCII code.
Why Encode URLs?
- Safety: Reserved characters like &, ?, = have special meaning in URLs
- Special Characters: Non-ASCII characters must be encoded for compatibility
- Spaces: URLs cannot contain spaces—they must be encoded as %20 or +
- API Calls: Query parameters often contain characters that need encoding
Encoding Methods
- encodeURIComponent: Encodes everything except A-Z, a-z, 0-9, - _ . ! ~ * ' ( )
- encodeURI: Preserves URL structure characters like : / ? # [ ] @
- Space as +: Form data encoding where spaces become + instead of %20
Common Use Cases
- Building API request URLs with query parameters
- Encoding form data for submission
- Creating bookmarklets and javascript: URLs
- Debugging URL-related issues