Developer Documentation
TypeScript
Updated September 19, 2026

URL Encoding and Decoding in TypeScript

Percent-encode URL components correctly and distinguish path, query, and form encoding in TypeScript.

URL encoding is context-sensitive. A path segment, a query value, and application/x-www-form-urlencoded data do not use exactly the same escaping rules, so prefer APIs designed for the specific component you are building.

Quick Start#

The following example uses the standard TypeScript API or a widely used package for this task.

Encode a component#

TypeScript
1function encodeComponent(value: string): string {2  return encodeURIComponent(value);3}45function decodeComponent(value: string): string {6  return decodeURIComponent(value);7}89const encoded = encodeComponent("café & tea + cake");

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Typed query builder#

TypeScript
1const params = new URLSearchParams();2params.set("q", "café & tea");3params.set("page", "1");45const url = new URL("https://example.com/search");6url.search = params.toString();

Important Notes#

Encode values, not an entire already-structured URL, unless you intentionally want to treat that URL as data inside another component.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement URL Encoding in other languages: