In JavaScript, you can use the btoa()
function to encode a string to Base64 and atob()
function to decode a Base64-encoded string back to its original form. Here's a simple example:
const originalString = 'Hello, World!';
// Encoding to Base64
const base64EncodedString = btoa(originalString);
console.log('Original String:', originalString);
console.log('Base64 Encoded String:', base64EncodedString);
Decoding (Base64 to String):
const base64EncodedString = 'SGVsbG8sIFdvcmxkIQ==';
// Decoding from Base64
const decodedString = atob(base64EncodedString);
console.log('Base64 Encoded String:', base64EncodedString);
console.log('Decoded String:', decodedString);
Remember that the btoa() and atob()
functions work with ASCII strings. If you try to encode non-ASCII characters, you might encounter issues. In that case, you may need to use btoa(unescape(encodeURIComponent(originalString)))
for encoding and decodeURIComponent(escape(atob(base64EncodedString)))
for decoding to handle non-ASCII characters correctly.
Here's an example that handles non-ASCII characters:
Encoding and Decoding with Non-ASCII Characters:
const originalString = '你好,世界!';
// Encoding to Base64 with non-ASCII characters
const base64EncodedString = btoa(unescape(encodeURIComponent(originalString)));
console.log('Original String:', originalString);
console.log('Base64 Encoded String:', base64EncodedString);
// Decoding from Base64 with non-ASCII characters
const decodedString = decodeURIComponent(escape(atob(base64EncodedString)));
console.log('Base64 Encoded String:', base64EncodedString);
console.log('Decoded String:', decodedString);
Always ensure that you handle encoding and decoding consistently, especially when dealing with special characters or when interoperating with other systems that might expect a specific format.