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.
Example
const inputString = "Homer Simpson!";
const base64Encoded = btoa(inputString);
console.log(base64Encoded);
Output
SG9tZXIgU2ltcHNvbiE=
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);
console.log(base64Encoded);
Output
SG9tZXIg5LiW55WMIQ==
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==’.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.