How to encode a String to base64 in JavaScript

To encode a string to base64 in JavaScript, you can use the built-in “btoa()” function. The “btoa()” function takes a string as its argument and returns a Base64-encoded version of the input string.


const inputString = "Homer Simpson!";
const base64Encoded = btoa(inputString);




In this code, we used the “btoa()” function to encode the inputString variable (‘Homer Simpson!’) to Base64, resulting in the string ‘SG9tZXIgU2ltcHNvbiE=’.

Remember that the “btoa()” function only works with “binary strings”, and if the input string contains characters outside the range of the 8-bit ASCII character set, it will throw an “InvalidCharacterError”.

To handle Unicode characters or strings with special characters, you need to convert the input string to a format that btoa() can process, such as UTF-8:

const inputString = 'Homer 世界!';
const utf8Encoded = unescape(encodeURIComponent(inputString));
const base64Encoded = btoa(utf8Encoded);




In this code, we first used the encodeURIComponent() method to convert the input string to a percent-encoded representation, then used unescape() method to convert it to a binary string that btoa() can process.

The resulting Base64-encoded string is ‘SGVsbG8sIOS4reWbveKcqA==’.

Leave a Comment