Lesson 50 +10 XP

HTML URL Encoding

HTML URL Encoding

URLs can only use a small set of safe characters. Special characters must be "encoded" so they can travel safely.

What is a URL?

A URL is a web address. It can only safely use letters, numbers, and a few symbols like -, _, ., and ~.

The problem with special characters

What if your page name is "My Page.html"? The space is a problem! Spaces and other symbols must be encoded.

Encoding rules

  • The browser converts every unsafe character to a % followed by two hex digits (its number code).
  • A space becomes %20.
<!-- A space in the filename -->
mypage.html?name=My Page

<!-- Encoded: -->
mypage.html?name=My%20Page

Common encodings

%20   space
%3C   <
%3E   >
%23   #
%25   %
%26   &
%2B   +
%3F   ?
%40   @

Example: sending data in a URL

https://example.com/search?q=best%20pizza%20in%20town

The %20 are the spaces between the words!

Reserved characters

Some characters are "reserved" in URLs because they have a special job:

  • ? starts the query (the part with data).
  • & separates pieces of data.
  • # jumps to a bookmark.

If you need one of THESE as actual data, it must be encoded!

Let the browser do the work

Usually you don't write encoded URLs by hand. Forms and JavaScript encode things for you. But it's good to understand what you see!

TL;DR

  • URLs safely use letters, numbers, and a few symbols.
  • Unsafe characters become %XX codes.
  • A space is %20.
  • ?, &, # have special jobs in URLs.
  • The browser (and your code) usually encodes for you.