Base64 Decoding in Javascript

In this article, you’ll learn how to decode a Base64 encoded data back to normal text in Javascript. Javascript has a built-in function named atob() which performs Base64 decoding. However, the atob() function doesn’t work properly if the encoded data contains DOMStrings which are 16-bit encoded. This article also shows how to handle UTF-16 strings.

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 😊

You can also use a javascript library to perform Base64 encoding and decoding. These libraries support encoding and decoding of unicode characters safely -

Also Read: Javascript Base64 Encode Example

References