HTML URL Encode
π What is URL Encoding?
URL Encoding (also called Percent Encoding) is the process of converting characters into a format that can be safely transmitted over the internet via a URL. It ensures that special characters don't interfere with the structure of URLs. π‘
>>βA properly encoded URL is the bridge between human-readable text and machine-readable communication.β π§
π€ Why is URL Encoding Important?
- π« URLs cannot contain spaces or certain symbols (like @, /, ?).
- β Encoding ensures URLs are valid and readable by browsers and servers.
- π Encoding helps support non-ASCII characters in URLs (e.g., emojis or foreign languages).
βοΈ How URL Encoding Works
URL encoding replaces unsafe characters with a % followed by two hexadecimal digits. For example, a space becomes %20.
Example of URL Encoding
Plain Text: Hello World!
Encoded URL: Hello%20World%21π Common Characters and Their Encoded Values
| Character | Encoded | Description |
|---|---|---|
| Space | %20 | Whitespace |
| ! | %21 | Exclamation mark |
| @ | %40 | At symbol |
| / | %2F | Forward slash |
| & | %26 | Ampersand |
| = | %3D | Equals sign |
π§ͺ Example in HTML
Letβs see how a URL with parameters is encoded in HTML:
Example HTML with Encoded URL
<a href="https://example.com/search?q=hello%20world%21">Search</a>Note
π‘ Browsers usually encode URLs automatically, but itβs good practice to encode query parameters when building URLs manually in code.
π οΈ Encoding with JavaScript
JavaScript provides built-in functions for encoding URLs:
JavaScript URL Encoding
const searchQuery = "hello world!";
const encoded = encodeURIComponent(searchQuery);
console.log(encoded); // Output: hello%20world%21
const fullURL = `https://example.com/search?q=${encoded}`;β Best Practices
- Use encodeURIComponent() when encoding individual query parameters.
- Use encodeURI() when encoding an entire URL (but not parameter keys/values individually).
- Avoid manually replacing characters; use built-in functions for reliability.
>>βEncode with careβURLs are the messengers of data on the web.β π