Back to KB
Difficulty
Intermediate
Read Time
4 min

URL Encoding Explained: Why %20 Means a Space (and When to Use encodeURIComponent)

By Codcompass TeamΒ·Β·4 min read

If you've ever built a URL with user input in it, you've hit this problem: spaces and special characters break everything. A URL like https://example.com/search?q=hello world is invalid β€” the space has to become %20. That transformation is URL encoding, and understanding when and how to do it correctly saves a lot of debugging time.

What Is URL Encoding?

URLs can only contain a defined set of safe characters: letters (A–Z, a–z), digits (0–9), and a handful of symbols (-, _, ., ~). Everything else β€” spaces, &, =, #, /, non-ASCII characters β€” must be encoded.

URL encoding replaces unsafe characters with a percent sign followed by two hex digits representing the character's ASCII (or UTF-8) value. So:

Character

Encoded

space

%20

&

%26

=

%3D

#

%23

/

%2F

Γ©

%C3%A9

The %C3%A9 for Γ© shows why it's not just ASCII β€” modern URL encoding uses UTF-8, where non-ASCII characters can span multiple bytes, each byte getting its own %XX escape.

The Two Forms You'll Actually Use

1. encodeURIComponent() β€” Encode a value

This is what you use for query parameter values and path segments. It encodes everything except letters, digits, -, _, ., and ~.

const query = "coffee & donuts";
const url = `https://example.com/search?q=${encodeURIComponent(query)}`;
// β†’ https://example.com/search?q=coffee%20%26%20donuts
`

πŸŽ‰ Mid-Year Sale β€” Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register β€” Start Free Trial

7-day free trial Β· Cancel anytime Β· 30-day money-back