How To Base64 Encode In Javascript

Base64 encoding is a widely used technique to convert binary data into a string representation that can be easily transmitted and stored. In this blog post, we’re going to explore how to perform Base64 encoding in JavaScript using the built-in window.btoa() function.

The window.btoa() Function

The window.btoa() function is a native JavaScript function that takes a binary string as its input and returns its Base64-encoded representation.

Here’s a simple example:

// Define the input string
const inputString = "Hello, World!";

// Encode the input string in Base64
const base64EncodedString = window.btoa(inputString);

// Output the encoded string
console.log(base64EncodedString); // "SGVsbG8sIFdvcmxkIQ=="

Encoding Non-ASCII Characters

The window.btoa() function only supports ASCII characters. If you need to encode a string with non-ASCII characters, you can use the encodeURIComponent() function to encode the string in UTF-8 before encoding it with window.btoa().

// Define the input string with non-ASCII characters
const inputString = "こんにちは、世界!";

// Encode the input string in UTF-8 and Base64
const base64EncodedString = window.btoa(encodeURIComponent(inputString).replace(/%([0-9A-F]{2})/g, (match, p1) => {
    return String.fromCharCode("0x" + p1);
}));

// Output the encoded string
console.log(base64EncodedString); // "44GT44KT44Gr44Gh44Gv44CB5aWz5LqM44GnIQ=="

Decoding Base64-encoded Strings

To decode a Base64-encoded string in JavaScript, you can use the window.atob() function. If the original string contained non-ASCII characters, you might need to use the decodeURIComponent() function to convert it back to its original form.

// Define the Base64-encoded string
const base64EncodedString = "44GT44KT44Gr44Gh44Gv44CB5aWz5LqM44GnIQ==";

// Decode the Base64-encoded string
const decodedString = decodeURIComponent(Array.prototype.map.call(window.atob(base64EncodedString), (c) => {
    return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
}).join(""));

// Output the decoded string
console.log(decodedString); // "こんにちは、世界!"

Conclusion

In this blog post, we’ve explored how to Base64 encode and decode strings in JavaScript using the window.btoa() and window.atob() functions. Additionally, we’ve seen how to handle non-ASCII characters by encoding and decoding them in UTF-8 using the encodeURIComponent() and decodeURIComponent() functions.