EN
JavaScript - base64 with Unicode support
9 points
In this short article, we would like to show how to encode text to base64 with Unicode support and back (decode base64) in JavaScript.

Quick solution (safe approach):
xxxxxxxxxx
1
var toUtf8 = function(text) {
2
var surrogate = encodeURIComponent(text);
3
var result = '';
4
for (var i = 0; i < surrogate.length;) {
5
var character = surrogate[i];
6
i += 1;
7
if (character == '%') {
8
var hex = surrogate.substring(i, i += 2);
9
if (hex) {
10
result += String.fromCharCode(parseInt(hex, 16));
11
}
12
} else {
13
result += character;
14
}
15
}
16
return result;
17
};
18
19
var fromUtf8 = function(text) {
20
var result = '';
21
for (var i = 0; i < text.length; ++i) {
22
var code = text.charCodeAt(i);
23
result += '%';
24
if (code < 16) {
25
result += '0';
26
}
27
result += code.toString(16);
28
}
29
return decodeURIComponent(result);
30
};
31
32
var Base64 = {
33
encode: function(text) {
34
return btoa(toUtf8(text));
35
},
36
decode: function(base64) {
37
return fromUtf8(atob(base64));
38
}
39
};
40
41
42
// Example:
43
44
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
45
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...
46
47
console.log(Base64.encode('日本')); // 5pel5pys
48
console.log(Base64.decode('5pel5pys')); // 日本
49
50
console.log(Base64.encode('I ❤️ JS')); // SSDinaTvuI8gSlM=
51
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ❤️ JS
Note:
escape
andunescape
methods are marked as not recommended to use so read about them here and here.
xxxxxxxxxx
1
var toUtf8 = function(text) {
2
return unescape(encodeURIComponent(text));
3
};
4
5
var fromUtf8 = function(text) {
6
return decodeURIComponent(escape(text));
7
};
8
9
var Base64 = {
10
encode: function(text) {
11
return btoa(toUtf8(text));
12
},
13
decode: function(base64) {
14
return fromUtf8(atob(base64));
15
}
16
};
17
18
19
// Example:
20
21
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
22
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...
23
24
console.log(Base64.encode('日本')); // 5pel5pys
25
console.log(Base64.decode('5pel5pys')); // 日本
26
27
console.log(Base64.encode('I ❤️ JS')); // SSDinaTvuI8gSlM=
28
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ❤️ JS