About URL Encoding
URL encoding, also known as percent-encoding, is a mechanism for converting characters into a format that can be safely transmitted in a URL. URLs can only contain a limited set of characters from the ASCII character set. Characters outside this set, or characters with special meaning in URLs (like &, =, ?, and #), must be encoded.
How Percent-Encoding Works
When a character needs to be encoded, it is replaced with a percent sign (%) followed by its two-digit hexadecimal ASCII value. For example:
- A space becomes %20 (or + in form data)
- An ampersand (&) becomes %26
- A question mark (?) becomes %3F
- A forward slash (/) becomes %2F
- Non-ASCII characters like emoji or accented letters are first encoded as UTF-8 bytes, then each byte is percent-encoded
When to Use URL Encoding
You need URL encoding in these situations:
- Query parameters: When passing user input in URL query strings, encoding prevents special characters from breaking the URL structure.
- API requests: RESTful API endpoints often require encoded parameters, especially for search queries or filter values.
- Form submissions: HTML forms with GET method encode field values in the URL automatically, but you may need manual encoding for AJAX requests.
- File paths: Filenames with spaces or special characters need encoding when used in URLs.
encodeURIComponent vs encodeURI
JavaScript provides two encoding functions with important differences:
- encodeURIComponent() encodes everything except: A-Z, a-z, 0-9, - _ . ! ~ * ' ( ). Use this for encoding individual query parameter values.
- encodeURI() preserves URL-structural characters like :, /, ?, #, and &. Use this for encoding an entire URL while keeping its structure intact.
This tool uses encodeURIComponent, which is the correct choice for encoding individual values that will be placed into URLs.