What is URL encoding?
URLs can only contain a limited set of ASCII characters. Anything else — spaces, &, =, ?, non-ASCII letters — must be percent-encoded. Each disallowed byte is replaced with % followed by its two-digit hex value. For example, a space becomes %20 and é becomes %C3%A9 (its UTF-8 byte sequence).
encodeURIComponent vs encodeURI
JavaScript exposes two built-ins with different escaping rules:
- encodeURIComponent encodes almost everything — safe for embedding a single value inside a query string or path segment.
- encodeURI preserves characters that are legal in a full URL (
:/?#[]@!amp;'()*+,;=), so it's meant for encoding an entire URL string without breaking its structure.
Rule of thumb: use encodeURIComponent when inserting a user-supplied value into a URL, and encodeURI when sanitizing an already-constructed URL.
Common examples
- hello world
- hello%20world
- a+b=c
- a%2Bb%3Dc
- café
- caf%C3%A9
- https://x.com/?q=a b
- https%3A%2F%2Fx.com%2F%3Fq%3Da%20b