The btoa()
method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob()
method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.
An ASCII string containing the Base64 representation of stringToEncode
.
const encodedData = btoa("Hello, world");
const decodedData = atob(encodedData);
Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which the code point of each character occupies only one byte. So if you pass a string into btoa()
containing characters that occupy more than one byte, you will get an error, because this is not considered binary data:
const ok = "a";
console.log(ok.codePointAt(0).toString(16));
const notOK = "✓";
console.log(notOK.codePointAt(0).toString(16));
console.log(btoa(ok));
console.log(btoa(notOK));
For how to work around this limitation when dealing with arbitrary Unicode text, see The "Unicode Problem" section of the Base64 glossary entry.