encodeURIComponent()

Percent-encodes a string so it is safe to use as a single URL path segment or query value.

Signature
encodeURIComponent(uriComponent)
  • Added in JavaScript ECMAScript 3 (1999)

Parameters

ParameterTypeDescription
$uriComponentstringA string to be encoded as a URI component — a path segment, query-string value, or fragment. Other values are converted to strings.

Return value

stringA new string with every character outside A–Z a–z 0–9 - _ . ! ~ * ' ( ) replaced by its UTF-8 percent-encoded form.

Errors

Throws URIError if the input contains a lone surrogate, which cannot be encoded as UTF-8.

encodeURIComponent() escapes everything that is not an unreserved URI character, which is the right level of aggression for a value that sits inside a URL. Crucially it escapes &, =, ?, # and / — the delimiters that would otherwise let a user-supplied value break out of its slot and inject an extra query parameter.

Component, not whole URL

Run it on each piece, never on the finished URL. Applying it to "https://example.com/a?b=c" mangles the scheme separator and the query into %3A%2F%2F and %3F. Use encodeURI() for a complete URL, and this function for the parts you interpolate into one.

Better still, do not build the string

When a URL or URLSearchParams object is available, let it do the encoding — it handles the delimiter rules for you and applies form encoding where that is correct.

Two edge cases

It leaves !, ', (, ) and * alone even though some servers treat them as reserved; escape those manually if your backend cares. And it encodes a space as %20, not +, so it is not a drop-in for application/x-www-form-urlencoded bodies.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Interpolate a user-typed search term into a query string without letting & split it in two.
  • Build a path segment from a title or slug that may contain slashes or spaces.
  • Encode a redirect target that will itself be carried as a query parameter.

Frequently asked questions

What is the difference between encodeURI and encodeURIComponent?

encodeURIComponent escapes the reserved delimiters ; / ? : @ & = + $ , # as well, so it is for values placed inside a URL; encodeURI leaves those intact so a complete URL stays usable. Encoding a whole URL with encodeURIComponent breaks it.

Does encodeURIComponent encode spaces as + or %20?

As %20. The + convention belongs to application/x-www-form-urlencoded, which URLSearchParams uses, so the two are not interchangeable for form bodies.

Why does encodeURIComponent throw a URIError?

Because the string contains a lone surrogate — half of a surrogate pair with no matching half — which has no valid UTF-8 encoding. Repair the string with String.prototype.toWellFormed() or replace the stray code unit before encoding.

More examples

Why a raw value is dangerous

Unencoded, the value smuggles in a second parameter. Encoded, the ampersand becomes %26 and stays part of the name. URLSearchParams produces the same protection, though it encodes spaces as + rather than %20.

Example · javascript
const evil = "x&admin=true";

console.log(`/api?name=${evil}`);
console.log(`/api?name=${encodeURIComponent(evil)}`);

// URLSearchParams does the same job and reads better
const params = new URLSearchParams({ name: evil, page: "1" });
console.log(params.toString());

Component versus whole URL

encodeURI escapes only the space and keeps the URL usable. encodeURIComponent escapes the colon, slashes, question mark and ampersand as well, producing a string that is a valid parameter value but no longer a URL.

Example · javascript
const url = "https://example.com/my docs?q=a&b";

console.log(encodeURI(url));
console.log(encodeURIComponent(url));

console.log(encodeURI("a&b=c"));          // a&b=c
console.log(encodeURIComponent("a&b=c")); // a%26b%3Dc

Round-tripping and the extra characters

The default output leaves ! ( ) * and ' as literal characters; the replace pass converts them to %21, %28, %29, %2A and %27 for servers that treat them as reserved. Both forms decode back to the original.

Example · javascript
const value = "50% off (today only)!";
const encoded = encodeURIComponent(value);
console.log(encoded);
console.log(decodeURIComponent(encoded) === value); // true

// Escape the characters it deliberately skips, if your server needs it
const strict = encoded.replace(/[!'()*]/g, (c) =>
  "%" + c.charCodeAt(0).toString(16).toUpperCase());
console.log(strict);

Discussion

  • Be the first to comment on this lesson.