About URL Encoding
URL encoding, also known as percent-encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI). It's used to convert characters that are not allowed in a URL into a format that can be transmitted over the Internet. This encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
Common Uses of URL Encoding
- Formatting query strings in URLs
- Sending form data via HTTP requests (application/x-www-form-urlencoded)
- Creating valid URLs with special characters or spaces
- Encoding non-ASCII characters in URLs
- Passing complex parameters in APIs and web services
How URL Encoding Works
URL encoding follows these principles:
- Alphanumeric characters (A-Z, a-z, 0-9) remain unchanged
- Special characters like space, ?, &, =, %, + are converted to their percent-encoded equivalents
- Each byte of a UTF-8 encoded character is percent-encoded separately
- A space character can be encoded as "%20" or "+" (in query parameters)
- Reserved characters like /, :, ?, #, [ have special meanings in URLs and may be treated differently depending on their context
encodeURI vs encodeURIComponent
JavaScript provides two functions for URL encoding:
- encodeURI: Encodes a complete URI, preserving characters that are part of the URI syntax (like /:?#[]@!$&'()*+,;=)
- encodeURIComponent: Encodes a URI component (like a query parameter value), encoding more characters including those with special meaning in a URI
For most cases when encoding user input or query parameters, encodeURIComponent()
is the safer option as it ensures all potentially problematic characters are properly encoded.
URL Encoding for International Characters
Modern browsers encode non-ASCII characters using UTF-8 encoding and then percent-encode each byte. This ensures that international characters, emojis, and other Unicode symbols can be properly included in URLs. For example, the Japanese character "日" is first UTF-8 encoded as three bytes (E6 97 A5) and then percent-encoded as "%E6%97%A5".
Examples
Plain Text | URL Encoded |
---|---|
Hello World | Hello%20World |
https://example.com/?q=search term | https%3A%2F%2Fexample.com%2F%3Fq%3Dsearch%20term |
50% off sale! | 50%25%20off%20sale%21 |
こんにちは | %E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF |