How to Decode a Base64 String in JavaScript

08/02/2021

Contents

In this article, you will learn how to decode a base64 string in JavaScript.

Decoding a base64 string in JavaScript

In JavaScript, you can decode a Base64 string using the atob() method. Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format.

Using the atob() method

The atob() method decodes a Base64 string to its original form. The method takes one argument: str. The str argument is the Base64 string to be decoded.

Example

const encodedStr = "SGVsbG8sIHdvcmxkIQ==";
const decodedStr = atob(encodedStr);
console.log(decodedStr); // "Hello, world!"

In this example, we decoded the Base64-encoded string “SGVsbG8sIHdvcmxkIQ==” to its original form using the atob() method.

Decoding non-ASCII characters

You can also decode Base64-encoded non-ASCII characters using the decodeURIComponent() and atob() methods. The decodeURIComponent() method decodes a URI-encoded string, and the atob() method decodes the result to its original form.

Example

const encodedStr = "JTI4JTgyJTk2JTI4JTIwJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTIzJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTI1JTNEJTIw";
const decodedStr = decodeURIComponent(Array.prototype.map.call(atob(encodedStr), function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
console.log(decodedStr); // "こんにちは、世界!"

In this example, we decoded the Base64-encoded string “JTI4JTgyJTk2JTI4JTIwJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTIzJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTI1JTNEJTIw” to its original form by first decoding it with the atob() method and then decoding the result with URI decoding using decodeURIComponent().

Encoding and decoding binary data

You can also encode and decode binary data using Base64. For example, you can encode an image file to Base64 and then decode it to display the image on a webpage.

Example

// Encoding binary data
const fileReader = new FileReader();
fileReader.onload = function(event) {
    const encodedData = btoa(event.target.result);
    console.log(encodedData);
};
fileReader.readAsBinaryString(file);

// Decoding Base64 data
const image = document.createElement('img');
image.src = "data:image/jpeg;base64," + encodedData;
document.body.appendChild(image);

In this example, we encoded binary data (in this case, an image file) to Base64 using the btoa() method and then decoded the Base64 data to display the image on a webpage.