HTML URL Encode

What is URL Encoding?

URL encoding (percent encoding) is a mechanism for encoding information in a URL. URLs can only contain ASCII characters (letters, digits, and a few special characters). Characters that are not allowed in URLs must be encoded using percent encoding (%XX where XX is the hexadecimal value).

Why URL Encoding is Needed

URLs can only contain ASCII characters. Special characters, spaces, and non-ASCII characters must be encoded:

Common URL Encoded Characters

Common characters that need URL encoding:

Character URL Encoded Description
Space %20 or + Space character
< %3C Less than
> %3E Greater than
& %26 Ampersand
" %22 Double quote
' %27 Single quote
/ %2F Forward slash
? %3F Question mark
# %23 Hash
= %3D Equals sign

URL Encoding Examples

Here are examples of URL encoding in action:

URLs with Spaces

Example
<!-- Spaces encoded as %20 -->
<a href="https://example.com/search?q=hello%20world">Search for "hello world"</a>

<!-- Spaces encoded as + (alternative) -->
<a href="https://example.com/search?q=hello+world">Search for "hello world"</a>

URLs with Special Characters

Example
<!-- URL with ampersand -->
<a href="https://example.com/page?name=John%26Doe">Page with & in URL</a>

<!-- URL with question mark -->
<a href="https://example.com/page?id=1%3Ftest">Page with ? in value</a>

JavaScript URL Encoding

JavaScript provides functions for URL encoding and decoding:

encodeURIComponent()

Encodes a URI component (query string value):

Example
<script>
    var search = 'hello world';
    var encoded = encodeURIComponent(search);
    console.log(encoded); // Output: hello%20world
    
    var url = 'https://example.com/search?q=' + encoded;
    console.log(url); // Output: https://example.com/search?q=hello%20world
</script>

decodeURIComponent()

Decodes a URI component:

Example
<script>
    var encoded = 'hello%20world';
    var decoded = decodeURIComponent(encoded);
    console.log(decoded); // Output: hello world
</script>

encodeURI()

Encodes a complete URI (but doesn't encode special characters that are part of URI syntax):

Example
<script>
    var uri = 'https://example.com/page?id=1&name=John Doe';
    var encoded = encodeURI(uri);
    console.log(encoded);
</script>

When to URL Encode

URL encoding is needed for:

URL Encoding in Forms

When forms are submitted via GET method, form values are automatically URL encoded:

Example
<form action="search.html" method="get">
    <input type="text" name="q" placeholder="Search...">
    <button type="submit">Search</button>
</form>
<!-- If user enters "hello world", URL becomes: search.html?q=hello+world -->

Best Practices