JavaScript (ES2026) reference · JSON and Global Functions

JavaScript encodeURIComponent() Function

Encode a string for use as one part of a URL (a query value or path segment), escaping &, =, ?, / and spaces.

JavaScript (ES2026) Since ES3

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

encodeURIComponent(string)

Parameters

ParameterDescription
string The text to encode.

Return value

An encoded string.

Examples

Encode a query valueTry it yourself
const q = "tea & cake?";
console.log(`https://example.com/search?q=${encodeURIComponent(q)}`);

Output

https://example.com/search?q=tea%20%26%20cake%3F
URLSearchParams does it for youTry it yourself
console.log(new URLSearchParams({ q: "tea & cake?", page: 2 }).toString());

Output

q=tea+%26+cake%3F&page=2

Version history

VersionChange
JavaScript ES3Added

In other languages

Was this page helpful?