HTML · Chapter 34 of 45

HTML URL Encoding

URLs can only contain a limited set of ASCII characters. URL encoding (percent-encoding) converts unsafe or reserved characters into a % followed by two hex digits, so URLs remain valid everywhere.

For example, a space becomes %20, and an ampersand within a query value becomes %26. Browsers and server frameworks usually handle this automatically, but understanding it helps debug broken links.

Syntax
encodeURIComponent("text")

Why encoding is needed

Characters like spaces, &, ?, and # have special meaning in URLs or aren't allowed at all, so they must be encoded to avoid breaking the link's structure.

Common encoded characters

Space becomes %20 (or +), & becomes %26, # becomes %23, and / becomes %2F when it needs to be literal rather than a path separator.

Example 1 (html)
<a href="https://example.com/search?q=hello%20world">Search</a>
Output
(navigates to a search for 'hello world')

%20 represents an encoded space within the URL query string.

Example 2 (javascript)
console.log(encodeURIComponent("a&b"));
Output
a%26b

encodeURIComponent() safely escapes special characters for use in a URL.

Key points

  • URLs only allow a limited set of ASCII characters safely.
  • Percent-encoding replaces unsafe characters with %XX hex codes.
  • Space becomes %20, & becomes %26, # becomes %23.
  • JavaScript's encodeURIComponent() automates this encoding.
💡 Note: Never manually concatenate untrusted user input into a URL without encoding it first.

📝 Quick Quiz

1. What does %20 represent in a URL?

2. Which JavaScript function URL-encodes a string?

3. Why is URL encoding necessary?