HTML URL Encode

Converting characters for safe URL transmission

🔗 What is URL Encoding?

URL encoding converts characters into a format that can be transmitted over the Internet. URLs can only be sent using ASCII characters, so special characters must be encoded using "%" followed by hexadecimal digits.


<!-- Original URL with spaces -->
https://example.com/search?q=hello world

<!-- URL Encoded (spaces become %20) -->
https://example.com/search?q=hello%20world
                                    

URL Encoding Basics

🔤

Why URL Encoding?

URLs can only contain ASCII characters

<!-- Problem: Special characters -->
https://site.com/search?q=café & restaurant

<!-- Solution: URL encoded -->
https://site.com/search?q=caf%C3%A9%20%26%20restaurant
📋

Common Encodings

Frequently used encoded characters

  • Space: %20
  • ! %21
  • " %22
  • # %23
  • $ %24
  • % %25
  • & %26
📝

Form Data Encoding

Forms automatically encode data

<form action="/search" method="get">
  <input type="text" name="query" value="John Doe">
  <input type="submit" value="Search">
</form>

Result URL:

/search?query=John%20Doe
🌐

JavaScript Encoding

Encode URLs with JavaScript

<script>
// Encode a URL component
let text = "hello world!";
let encoded = encodeURIComponent(text);
console.log(encoded); // "hello%20world%21"

// Decode back
let decoded = decodeURIComponent(encoded);
console.log(decoded); // "hello world!"
</script>

🔹 When URL Encoding is Needed

URL encoding is required in several situations:

Characters that MUST be encoded:

  • Spaces: Cannot appear in URLs
  • Reserved characters: : / ? # [ ] @ ! $ & ' ( ) * + , ; =
  • Unsafe characters: " < > % \ ^ ` { | }
  • Non-ASCII characters: Characters outside ASCII range
<!-- Example: Search form with special characters -->
<form action="/search" method="get">
  <input type="text" name="q" placeholder="Search for 'cats & dogs'">
  <input type="submit" value="Search">
</form>

<!-- When submitted with "cats & dogs", becomes: -->
<!-- /search?q=cats%20%26%20dogs -->

🔹 Practical Examples

Real-world URL encoding scenarios:

🔸 Email Links

<!-- Email with subject and body -->
<a href="mailto:[email protected]?subject=Hello%20World&body=This%20is%20a%20test%20message">
  Send Email
</a>

Output:

🔸 Social Media Sharing

<!-- Twitter share link -->
<a href="https://twitter.com/intent/tweet?text=Check%20out%20this%20awesome%20website%21&url=https%3A//example.com">
  Share on Twitter
</a>

🧠 Test Your Knowledge

What does %20 represent in URL encoding?