Base64 Decoding in Javascript

Javascript Base64 Decode Example

Javascript contains a built-in function called window.atob() to decode any Base64 encoded data back to binary data -

var encodedStr = "SGVsbG9AV29ybGQ=";

// Decode the String
var decodedStr = atob(encodedStr);
console.log(decodedStr);    // Hello@World

The above function works flawlessly if the Base64 encoded input only had 8-bit bytes. However, it doesn’t work properly if the encoded input had 16-bit Unicode characters.

var encodedStr = "SGVsbG8g8J+Yig==";    // Encoding of 'Hello 😊'

// Decode the String
var decodedStr = atob(encodedStr);
console.log(decodedStr);    // "Hello 😊   "

Javascript Generic Base64 decode with support for 16-bit encoded (UTF-16) strings

One way to handle Unicode DOM strings is to convert the Base64 encoded bytes to percent-encoded strings and then decode the percent encoded string using decodeURIComponent() like this -

function base64DecodeUnicode(str) {
    // Convert Base64 encoded bytes to percent-encoding, and then get the original string.
    percentEncodedStr = atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join('');


    return decodeURIComponent(percentEncodedStr);
}

console.log(base64DecodeUnicode('SGVsbG8g8J+Yig=='))  // Hello 😊

Check out another solution to the Unicode problem in the following article by Mozilla -

Base64 Decoding: Solving the Unicode Problem

Also Read: Javascript Base64 Encode Example

References