Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format.
This can be useful for representing images, files or other data that doesn’t fit well into a text-based format.
In this blog post, we’ll learn how to encode data in Base64 using JavaScript.
Encoding Base64 with JavaScript
JavaScript provides a native method called window.btoa() to perform Base64 encoding.
This method takes a string as an input and returns a Base64-encoded ASCII string.
Here’s an example of how to use window.btoa():
const text = "Hello, World!"; const base64Encoded = window.btoa(text); console.log(base64Encoded); // "SGVsbG8sIFdvcmxkIQ=="
Encoding non-ASCII characters
The window.btoa() method only works correctly with ASCII strings.
If you want to encode a string containing non-ASCII characters, you can use the encodeURIComponent() function to first encode the string as UTF-8 and then encode it in Base64.
const text = "こんにちは、世界!"; const utf8Encoded = encodeURIComponent(text); const base64Encoded = window.btoa(utf8Encoded); console.log(base64Encoded); // "JUUzJTgwJTk2JUUzJUEwJTkxJUUzJUFEJTg1JTBEJUUzJUEwJTk3JUUzJTgwJTk2JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTAwJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4"
Decoding Base64 with JavaScript
To decode a Base64-encoded string in JavaScript, you can use the window.atob() method.
This method takes a Base64-encoded ASCII string as input and returns the original string.
const base64Encoded = "SGVsbG8sIFdvcmxkIQ=="; const text = window.atob(base64Encoded); console.log(text); // "Hello, World!"
Decoding non-ASCII characters
If you want to decode a Base64-encoded string containing non-ASCII characters, you’ll need to first decode it using window.atob() and then decode the UTF-8 encoding using decodeURIComponent().
const base64Encoded = "JUUzJTgwJTk2JUUzJUEwJTkxJUUzJUFEJTg1JTBEJUUzJUEwJTk3JUUzJTgwJTk2JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTgwJTk4JUUzJTAwJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4JUUzJUFEJTk4"; const utf8Encoded = window.atob(base64Encoded); const text = decodeURIComponent(utf8Encoded); console.log(text); // "こんにちは、世界!"
Conclusion
In this blog post, we’ve learned how to encode and decode Base64 in JavaScript using window.btoa() and window.atob() methods.
We’ve also covered how to handle non-ASCII characters by encoding and decoding them as UTF-8 using encodeURIComponent() and decodeURIComponent().