EN
JavaScript - encode / escape URL characters
25 points
In this short article, we would like to show how in JavaScript, use encodeURIComponent()
function to escape all unsafe characters in some URL.
Quick solution:
xxxxxxxxxx
1
const url = `/?message=${encodeURIComponent('How are you?')}`;
2
3
console.log(url); // /?message=How%20are%20you%3F
or:
xxxxxxxxxx
1
const message = 'Hi! This is some message...';
2
const url = `https://my-domain.com/chat?message=${encodeURIComponent(message)}`;
3
4
console.log(url); // https://my-domain.com/chat?message=Hi!%20This%20is%20some%20message...
encodeURIComponent()
function converts/escapes characters in the following way:
|
|
Runnable examples:
xxxxxxxxxx
1
// Not escaped characters:
2
3
console.log(encodeURIComponent(`0123456789`)); // 0123456789
4
console.log(encodeURIComponent(`abcdefghijklmnopqrstuvwxyz`)); // abcdefghijklmnopqrstuvwxyz
5
console.log(encodeURIComponent(`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
6
console.log(encodeURIComponent(`~!*-_.'()`)); // ~!*-_.'()
7
8
// Some escaped characters:
9
10
console.log(encodeURIComponent(`日本`)); // %E6%97%A5%E6%9C%AC
11
console.log(encodeURIComponent(`Россия`)); // %D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F
12
console.log(encodeURIComponent(`ąćęłńóśźż`)); // %C4%85%C4%87%C4%99%C5%82%C5%84%C3%B3%C5%9B%C5%BA%C5%BC
13
console.log(encodeURIComponent(`@:/?#&=`)); // %40%3A%2F%3F%23%26%3D
14
console.log(encodeURIComponent(`🚀🍏🍌❤️💻🙂`)); // %F0%9F%9A%80%F0%9F%8D%8F%F0%9F%8D%8C%E2%9D%A4%EF%B8%8F%F0%9F%92%BB%F0%9F%99%82
15
console.log(encodeURIComponent(` \t\n`)); // %20%09%0A