URL Encoding
Overview
URLs (web addresses) can only be sent over the internet using a very specific set of safe characters (like standard letters and numbers).
If you have a URL that contains unsafe characters—like a space, an ampersand (&), or foreign language characters—the browser has to translate them into a safe format before sending them. This translation is called URL Encoding (or Percent-encoding).
Syntax
You cannot have a literal space in a URL. When an HTML form submits data with a space, or if you create a link with a space in it, the browser converts the space into `%20` or a plus sign `+`.
<!-- ❌ WRONG: Spaces in href will break in some systems -->
<a href="/search?q=hello world">Search</a>
<!-- ✅ CORRECT: The space is encoded as %20 -->
<a href="/search?q=hello%20world">Search</a>When you submit an HTML `<form>`, the browser automatically encodes all the input data for you. You don't have to do it manually!
<!-- If the user types "Fish & Chips" into the search box... -->
<form action="/search" method="GET">
<input type="text" name="food" />
<button type="submit">Search</button>
</form>
<!-- ...The browser automatically visits this URL: -->
<!-- /search?food=Fish+%26+Chips -->
<!-- (Space became +, and '&' became %26) -->Common Pitfalls
- In modern JavaScript, you don't need to memorize these codes. You can just use the built-in `encodeURIComponent('Fish & Chips')` function, and it will handle the complex translation for you!
Real-World Example
A pre-filled email link requires URL encoding for the subject and body to handle spaces and new lines properly:
<!--
%20 = Space
%3F = Question Mark (?)
%0A = New Line (Enter)
-->
<a href="mailto:support@example.com?subject=Need%20Help%3F&body=Hello%2C%0AI%20need%20assistance.">
Email Support
</a>