
Definition:
URL Encoding (also called percent encoding) is the process of converting characters into a format that can be safely transmitted over the internet in a URL.
Some characters in URLs are reserved for special meanings (e.g., ?
, &
, /
), and some are not allowed (like spaces), so they must be encoded.
1. Why URL Encoding is Needed
- URLs can only contain letters (
A–Z
,a–z
), digits (0–9
), and a few special characters (- _ . ~
). - Any other characters (spaces, punctuation, symbols, Unicode) must be encoded as
%
followed by two hexadecimal digits.
Example:
Space → %20
@ → %40
₹ → %E2%82%B9
2. How URL Encoding Works
- Reserved/unsafe characters are replaced with a percent sign (
%
) + two hexadecimal values representing the character’s ASCII/UTF-8 code. - Example:
"Hello World!"
becomes:
Hello%20World%21
- Encoding ensures safe transmission in query strings, form submissions, and hyperlinks.
3. Common URL Encodings List
Character | Encoded Value | Description |
---|---|---|
Space | %20 or + | Whitespace |
! | %21 | Exclamation |
# | %23 | Hash (anchor) |
$ | %24 | Dollar sign |
% | %25 | Percent |
& | %26 | Ampersand |
( | %28 | Left parenthesis |
) | %29 | Right parenthesis |
* | %2A | Asterisk |
+ | %2B | Plus sign |
, | %2C | Comma |
/ | %2F | Forward slash |
: | %3A | Colon |
; | %3B | Semicolon |
= | %3D | Equals sign |
? | %3F | Question mark |
@ | %40 | At symbol |
[ | %5B | Left square bracket |
] | %5D | Right square bracket |
4. Example in HTML
<!DOCTYPE html>
<html>
<body>
<h2>URL Encoding Example</h2>
<!-- Link with space (encoded) -->
<a href="https://example.com/search?q=Hello%20World">
Search for "Hello World"
</a>
<!-- Form that submits encoded values -->
<form action="https://example.com/search" method="get">
<input type="text" name="q" value="HTML & CSS">
<input type="submit" value="Search">
</form>
<!-- Encoded URL in JavaScript -->
<script>
let text = "HTML & CSS";
let encoded = encodeURIComponent(text);
console.log(encoded); // HTML%20%26%20CSS
</script>
</body>
</html>
5. Functions for URL Encoding
- JavaScript:
encodeURI(url)
→ Encodes a full URL but keeps: / ? # &
safe.encodeURIComponent(str)
→ Encodes every unsafe character.
- Server-side languages (PHP, Python, Java, etc.) have similar functions (
urlencode
,urllib.parse.quote
, etc.).