Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

encodeURIComponent

Encodes text for safely putting it into part of a URL.

Available since: ES3

Syntax

encodeURIComponent(str)

Parameters

ParameterTypeDescription
strstringThe text to put into a URL.

Return value

stringThe string with special characters replaced by codes like %20.

Examples

Spaces, ampersands and non-Latin characters:

console.log(encodeURIComponent('rock & roll'));
console.log(encodeURIComponent('café'));

Output:

rock%20%26%20roll
caf%C3%A9

A search parameter in a URL:

const query = 'tea & cake';
const url = `https://example.com/search?q=${encodeURIComponent(query)}`;
 
console.log(url);

Output:

https://example.com/search?q=tea%20%26%20cake

Notes

Without encoding the & in the value would split the parameter in two. For whole addresses there is encodeURI(): it leaves /, ? and & alone. The most convenient way to build parameters is URLSearchParams, which encodes by itself.

See also

  • decodeURIComponent — Decodes text that was encoded for a URL.
  • URLSearchParams — Reads and builds URL query parameters (the part after ?).
  • URL — Parses an address into parts and builds it back.

Related recipes

In the tutorial

  • Server requests: fetch — The fetch function in JavaScript: GET and POST requests, the response object, status, response.ok, parsing JSON and handling errors.

Thanks for reading!

Donate to the site — we work hard for you.