What Is URL Encoding?
URL encoding (formally called percent encoding) is the process of converting characters that are not allowed or have special meaning in URLs into a universally safe format. The process replaces each unsafe character with a % sign followed by two hexadecimal digits representing the character's byte value. For example, a space becomes %20, an ampersand becomes %26, and the at sign becomes %40.
This standard is defined in RFC 3986 and is essential for safely transmitting data in URLs. Without encoding, browsers and servers would misinterpret characters like & (parameter separator), = (key-value separator), and ? (query start) as structural URL elements rather than literal data values.
encodeURI vs encodeURIComponent
JavaScript provides two encoding functions that behave very differently and are suited for different use cases:
| Character | encodeURI() | encodeURIComponent() | Context |
|---|---|---|---|
| https:// | Preserved | Encoded %3A%2F%2F | encodeURI preserves protocol |
| ?query=x | Preserved | Encoded | encodeURI preserves query structure |
| hello world | hello%20world | hello%20world | Both encode spaces |
| #section | Preserved | Encoded %23section | Use encodeURIComponent for values |
| a&b=c | Preserved | a%26b%3Dc | Encode param values with URIComponent |
| email@x.com | email@x.com | email%40x.com | @ is safe in URI but encoded in Component |
Use encodeURI() when:
- Encoding a complete URL for use in an href attribute
- Preserving the URL's structure (protocol, slashes, query markers)
- Encoding a URL before navigation or redirect
Use encodeURIComponent() when:
- Encoding a value that will be inserted as a query parameter
- Encoding a redirect URL inside another URL's query string
- Encoding form field values, search terms, or API request parameters
Common URL Encoding Mistakes
✗ Double-encoding URLs
→ If a URL is already encoded, encoding it again turns %20 into %2520. Always decode first, then re-encode if needed.
✗ Using encodeURI for query values
→ encodeURI() doesn't encode & = # ? which have special meaning in query strings. Use encodeURIComponent() for values inside query parameters.
✗ Encoding entire redirect URLs with encodeURI()
→ A redirect URL embedded as a query parameter value must be encoded with encodeURIComponent() to prevent it from being parsed as part of the parent URL's query string.
✗ Using + instead of %20 in URLs
→ + as a space encoding is only valid in application/x-www-form-urlencoded form data. Use %20 in URL paths and query strings for proper RFC 3986 compliance.
✗ Not encoding user-generated input in URLs
→ Any user input placed into a URL without encoding is a potential injection vulnerability. Always encode dynamic values before appending them to URLs.