Languages
[Edit]
EN

JavaScript - base64 with Unicode support

9 points
Created by:
JustMike
28920

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

Base64 with unicode support in JavaScript
Base64 with unicode support in JavaScript

Quick solution (safe approach):

// ONLINE-RUNNER:browser;

var CODE_EXPRESSION = /%([0-9A-F]{2})/g;

var getChar = function(part, hex) {
  	return String.fromCharCode(parseInt(hex, 16));
};

var encodeUnicode = function(text) {
  	var safeText = encodeURIComponent(text);
  	return safeText.replace(CODE_EXPRESSION, getChar);
};

var decodeUnicode = function(text) {
  	var result = '';
    for (var i = 0; i < text.length; ++i) {
        var code = text.charCodeAt(i);
        result += '%';
        if (code < 16) {
          	result += '0';
        }
        result += code.toString(16);
    }
    return decodeURIComponent(result);
};

var Base64 = {
    encode: function(text) {
        return btoa(encodeUnicode(text));
    },
    decode: function(base64) {
        return decodeUnicode(atob(base64));
    }
};

// Example:

console.log(Base64.encode('This is text...'));      // VGhpcyBpcyB0ZXh0Li4u
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...

console.log(Base64.encode('ŠŚąŠťČ'));      // 5pel5pys
console.log(Base64.decode('5pel5pys')); // ŠŚąŠťČ

console.log(Base64.encode('I ÔŁĄ´ŞĆ JS'));          // SSDinaTvuI8gSlM=
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ÔŁĄ´ŞĆ JS

Web browser methods based approach

Note: escape and unescape methods are marked as not recommended to use so read about them here and here.

// ONLINE-RUNNER:browser;

var encodeUnicode = function(text) {
  	return unescape(encodeURIComponent(text));
};

var decodeUnicode = function(text) {
  	return decodeURIComponent(escape(text));
};

var Base64 = {
    encode: function(text) {
      	return btoa(encodeUnicode(text));
    },  
  	decode: function(base64) {
        return decodeUnicode(atob(base64));
    }
};

// Example:

console.log(Base64.encode('This is text...'));      // VGhpcyBpcyB0ZXh0Li4u
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...

console.log(Base64.encode('ŠŚąŠťČ'));      // 5pel5pys
console.log(Base64.decode('5pel5pys')); // ŠŚąŠťČ

console.log(Base64.encode('I ÔŁĄ´ŞĆ JS'));          // SSDinaTvuI8gSlM=
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ÔŁĄ´ŞĆ JS

References

  1. btoa - MDN docs
  2. base64.js - NPM Page
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join