Encode to a Base64 string
btoa()
(binary to ASCII) method takes a binary JavaScript string (each character occupies only one byte) as a parameter to create a Base64 encoded string (which represents binary data in an ASCII string).
Troubleshooting: The string to be encoded contains characters outside of the Latin1 range.
If the string you pass into btoa()
contains characters that occupy more than one byte, you will get an error as below:
Code:
console.log(btoa('✓✓'));
Error:
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
To encode a Unicode string, MDN: btoa provides a method which gets each code unit of the Unicode string to create a new string.
Here is a more simple method which converts the Unicode string with encodeURI()
.
console.log(btoa(encodeURI('✓✓'));
Note you will have to reverse the conversion on the decoded string:
let encodedStr = btoa(encodeURI('✓✓')); // 'JUUyJTlDJTkzJUUyJTlDJTkz'
let decodedStr = decodeURI(atob(encodedStr));
console.log(decodedStr); // '✓✓'
Decode a Base64 encoded string
Use atob()
to decode a Base64 encoded string.
let encodedStr = btoa(('hello'));
let decodedStr = atob(encodedStr);
console.log(decodedStr); // 'hello'
If the original binary string contains characters beyond the Latin range, call decodeURI()
after atob()
.
let encodedStr = btoa(encodeURI('✓✓'); // 'JUUyJTlDJTkzJUUyJTlDJTkz'
let decodedStr = decodeURI(atob(encodedStr));
console.log(decodedStr); // '✓✓'