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