HTML URL Encode

URLs can only be sent over the Internet using a limited set of ASCII characters. Spaces, non-Latin letters, and many punctuation symbols are not allowed to appear as-is inside a URL, so they must first be converted into a safe format called percent-encoding (also known as URL encoding).

1) Why URLs Need Encoding


<!-- Not safe: contains a space and an ampersand -->
https://example.com/search?q=html tutorial&lang=en

<!-- Safe: percent-encoded -->
https://example.com/search?q=html%20tutorial&lang=en

Certain characters are reserved because they have a special meaning inside a URL — for example & separates query parameters and # starts a fragment. If your data itself contains these characters, they must be encoded so the browser and server do not misinterpret the URL's structure.

2) Percent-Encoding Basics


<!-- Space becomes %20 (or + inside a query string) -->
My Documents  →  My%20Documents

<!-- & becomes %26 -->
Rock & Roll  →  Rock%20%26%20Roll

<!-- # becomes %23 -->
Section #1   →  Section%20%231

Percent-encoding replaces an unsafe character with a % followed by the character's two-digit hexadecimal code. For example, a space is character code 32 in hex 20, giving %20. Inside the query string portion of a URL, a space may also be written as +.

3) Reference Table of Common Encoded Characters

Below is a quick reference for some of the most frequently encoded characters:

CharacterEncoded
space%20 (or +)
!%21
"%22
#%23
$%24
%%25
&%26
'%27
+%2B
,%2C
/%2F
:%3A
;%3B
=%3D
?%3F
@%40

4) Form Example: Encoding a GET Request


<form action="search.php" method="get">
  <label for="q">Search:</label>
  <input type="text" id="q" name="q">
  <input type="submit" value="Search">
</form>

When this form is submitted with the value HTML & CSS typed into the search box, the browser automatically encodes it before adding it to the URL:


search.php?q=HTML%20%26%20CSS

Notice the space became %20 and the & became %26 so it is not mistaken for a separator between two different query parameters.

Best Practices:

  • Browsers automatically encode form submissions and typed addresses, but you should still encode data manually when building URLs in code.
  • In JavaScript, encodeURIComponent() safely encodes a single value for use inside a query string — you will meet this function in the JavaScript tutorial section.
  • Never manually concatenate untrusted user input into a URL without encoding it first — unencoded reserved characters can break the URL or introduce security issues.
  • Reserved characters such as &, =, and ? should only appear unencoded when they are being used for their actual reserved purpose (separating parameters, etc.).