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:
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:
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.
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.