← All articles

Web platform

URL encoding explained

Understand components and percent encoding.

On this page

  1. Separate the components
  2. Encode individual values
  3. Avoid double encoding

Separate the components

A URL can contain a scheme, host, path, query and fragment. Different components have different escaping rules.

Encode individual values

encodeURIComponent is useful for individual query values, while URLSearchParams builds query strings without manual concatenation.

Avoid double encoding

Encoding an already encoded value changes percent signs into %25. Decode only when appropriate and handle malformed sequences.

Example

const url = new URL("https://example.com/search");
url.searchParams.set("q", "HTML & CSS");
console.log(url.href);

Related reading