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%3FDecoding
decodeURIComponent() does the opposite:
console.log(decodeURIComponent('Caf%C3%A9%20%26%20bar'));Output:
Café & barencodeURI
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%3D2Common 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:
TomFunctions used in this recipe
- encodeURIComponent — Encodes text for safely putting it into part of a URL.
- URLSearchParams — Reads and builds URL query parameters (the part after ?).