EN
JavaScript - decode url characters
10 points
In this short article, we would like to show how in JavaScript, use decodeURIComponent()
function to decode escaped unsafe characters in some URLs.
Hint: to know more about what characters are encoded/decoded read this article.
Quick solution:
xxxxxxxxxx
1
const message = 'Hi!%20This%20is%20some%20message...';
2
const decodedMessage = decodeURIComponent(message);
3
4
console.log(decodedMessage ); // Hi! This is some message...
Where:
message
value could be located in some URL:xxxxxxxxxx
1https://my-domain.com/chat?message=Hi!%20This%20is%20some%20message...
message
value can be extracted using:String
split()
method (link here),RegExp
class (documentation link here),- built-in
URL
class (documentation link here), - some custom library (e.g query-string library).
In this section, you will find some example characters that must be encoded, and those that are not.
xxxxxxxxxx
1
// Not encoded/decoded characters:
2
3
console.log(decodeURIComponent(`0123456789`)); // 0123456789
4
console.log(decodeURIComponent(`abcdefghijklmnopqrstuvwxyz`)); // abcdefghijklmnopqrstuvwxyz
5
console.log(decodeURIComponent(`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
6
console.log(decodeURIComponent(`~!*-_.'()`)); // ~!*-_.'()
7
8
// some encoded/decoded characters:
9
10
console.log(decodeURIComponent(`%E6%97%A5%E6%9C%AC`)); // 日本
11
console.log(decodeURIComponent(`%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F`)); // Россия
12
console.log(decodeURIComponent(`%C4%85%C4%87%C4%99%C5%82%C5%84%C3%B3%C5%9B%C5%BA%C5%BC`)); // ąćęłńóśźż
13
console.log(decodeURIComponent(`%40%3A%2F%3F%23%26%3D`)); // @:/?#&=
14
console.log(decodeURIComponent(`%F0%9F%9A%80%F0%9F%8D%8F%F0%9F%8D%8C`)); // 🚀🍏🍌
15
console.log(decodeURIComponent(`%E2%9D%A4%EF%B8%8F%F0%9F%92%BB%F0%9F%99%82`)); // ❤️💻🙂
16
console.log(decodeURIComponent(`%20%09%0A`)); // \t\n