Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to encode text for a URL

Short answer

encodeURIComponent() replaces spaces, ampersands and other special characters with codes so they do not break the address:

const query = 'tea & coffee?';
 
console.log('/search?q=' + encodeURIComponent(query));

Output:

/search?q=tea%20%26%20coffee%3F

Decoding

decodeURIComponent() does the opposite:

console.log(decodeURIComponent('Caf%C3%A9%20%26%20bar'));

Output:

Café & bar

encodeURI

encodeURI() encodes a whole address and leaves the characters that have a meaning in it, such as /, ? and &:

console.log(encodeURI('https://example.com/my page?a=1&b=2'));
console.log(encodeURIComponent('https://example.com/my page?a=1&b=2'));

Output:

https://example.com/my%20page?a=1&b=2
https%3A%2F%2Fexample.com%2Fmy%20page%3Fa%3D1%26b%3D2

Common mistake

Gluing a value into an address without encoding loses part of the data. The ampersand is read as the start of the next parameter:

const name = 'Tom & Jerry';
const params = new URLSearchParams('q=' + name);
 
console.log(params.get('q'));

Output:

Tom

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.