Languages
[Edit]
EN

JavaScript - base64 with Unicode support

9 points
Created by:
Remy-Lebe
502

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 encodeUnicode = function(text) {
  	var surrogate = encodeURIComponent(text);
  	var result = '';
    for (var i = 0; i < surrogate.length;) {
        var character = surrogate[i];
		i += 1;
        if (character == '%') {
        	var hex = surrogate.substring(i, i += 2);
			if (hex) {
				result += String.fromCharCode(parseInt(hex, 16));
			}
        } else {
        	result += character;
        }
    }
    return result;
};

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