How to Encode and Decode Strings with Base64 in JavaScript

In this tutorial, you will learn how to encode a string to Base64 encoded format. Javascript provides a built-in function named btoa() (binary-to-ASCII) to perform Base64 encoding.

Let's see how you can encode a string by using the btoa() function:

Javascript btoa() to perform Base64 encoding
let str = "Hello People"; // Encode the String let encodedString = btoa(str); console.log(encodedString); // SGVsbG8gUGVvcGxl

Also, check our Base64 Encoder tool.

The default btoa() function works well for binary data consisted of 8-bit bytes(UTF-8).

However, the btoa() function accepts a string where each character represents an 8-bit byte. If a string contains characters that can't be represented in 8 bits(e.g. UTF16), it will break.

To handle Unicode characters, you need, firstly, to escape the string to an array of 8-bit bytes and then use the window.btoa() function to encode to Base64:

Javascript btoa() to perform Base64 encoding
function base64EncodeUnicode(str) { // Firstly, escape the string using encodeURIComponent to get the UTF-8 encoding of the characters, // Secondly, we convert the percent encodings into raw bytes, and add it to btoa() function. utf8Bytes = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode('0x' + p1); }); return btoa(utf8Bytes); } console.log(base64EncodeUnicode('Hello People')) // SGVsbG8gUGVvcGxl

There is a counterpart function atob() to convert from base64 encoding to string. The atob() function returns a string where each character represents an 8-bit byte, meaning its value will be between 0 and 0xff.

Javascript atob() to perform Base64 encoding
let str = "Hello People"; let enc = btoa(str); console.log(enc); // Outputs: "SGVsbG8gUGVvcGxl" let dec = atob(enc); console.log(dec); // Outputs: "Hello People"

Check out Base 64 Decoder tool.

Base64 encoding and decoding

Base64 is a collection of binary-to-text encoding schemes representing binary data during an ASCII string format by translating it into a radix-64 representation. Base64 is an encoding algorithm allowing to convert any characters into an alphabet, which consists of Latin letters, digits, plus, and slash. In JavaScript, there are two functions for decoding and encoding base64 strings: btoa() which is used to create a base-64 encoded ASCII string from a string of binary data and atob(), which decodes a base64 encoded string.