The JavaScript btoa()
method only supports characters that can be represented using a single byte (8-bits). This means that it only supports a total of 256 characters from the following character sets:
- 128 characters of the ASCII character set, and;
- 128 additional characters from the Latin-1 (ISO-8859-1) character set.
Essentially, Latin-1 is a superset of ASCII, meaning that any valid ASCII character is also a valid Latin-1 character. It includes the ASCII characters in the first 128 slots, and the additional 128 slots contain characters such as accented letters, currency symbols, and other special characters used in Western European languages.
For example:
// ES5+ const encodedStr = btoa('foobar'); console.log(encodedStr); // 'Zm9vYmFy'
If you pass a string that is not in this range to the btoa()
method, it will throw an error:
// ES5+
// Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
btoa('🦊');
To support multibyte strings, you can convert the original string to binary format so that it can be used with the btoa()
method for Base64 encoding.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.