In JavaScript, you can easily encode a string to Base64 using the btoa()
function. Here’s how to do it:
Using btoa()
Function
The btoa()
function encodes a string to Base64. This function takes a string as an argument and returns the Base64 encoded version of that string.
Example:
// String to encode
const str = "Hello, World!";
// Encode the string to Base64
const encoded = btoa(str);
console.log(encoded); // Outputs: SGVsbG8sIFdvcmxkIQ==
Important Notes:
btoa()
only works with ASCII strings (i.e., characters with codes in the range 0-255). If you try to usebtoa()
on a string containing characters that are outside this range (like UTF-8 characters), it will throw an error.- To handle non-ASCII characters (like UTF-8 encoded characters), you need to first convert the string into a compatible format (e.g., by encoding it as a UTF-8 byte sequence).
Handling Non-ASCII Characters
To handle Unicode or non-ASCII characters properly, you can use encodeURIComponent()
to ensure the string is properly encoded before passing it to btoa()
.
Example:
// String with special characters
const str = "こんにちは"; // "Hello" in Japanese
// Encode the string in Base64
const encoded = btoa(unescape(encodeURIComponent(str)));
console.log(encoded); // Base64 encoded result
Here:
encodeURIComponent(str)
encodes the string to a URL-safe encoding, ensuring all characters are represented correctly.unescape()
reverses any percent-encoding, allowing thebtoa()
function to encode it to Base64.
Decoding Base64
To decode a Base64 encoded string, you can use the atob()
function, which is the reverse of btoa()
:
const decoded = atob(encoded);
console.log(decoded); // Outputs: こんにちは
Summary
- Use
btoa()
for encoding a string to Base64 (ensure the string contains only ASCII characters). - For non-ASCII characters, first use
encodeURIComponent()
andunescape()
to handle the encoding properly before usingbtoa()
. - Use
atob()
to decode Base64 strings back into their original form.