Explain Codes LogoExplain Codes Logo

How can you encode a string to Base64 in JavaScript?

javascript
base64-encoding
javascript-functions
utf-8
Anton ShumikhinbyAnton Shumikhin·Dec 8, 2024
TLDR

To encode a string to Base64 in JavaScript, simply call btoa():

let base64 = btoa('Victory is mine!'); console.log(base64); // Outputs TmljZSB0cnkg: The encoded "Victory is mine!"... or maybe a potion recipe. Who knows?

There you go: pass your original string to btoa() and voila, you get your encoded Base64!

Encoding non-ASCII Characters

When dealing with non-ASCII characters, you'd want to encode them as UTF-8 before converting them to Base64.

function utf8EncodeAndToBase64(str) { return btoa(encodeURIComponent(str)); } let utf8ThenBase64 = utf8EncodeAndToBase64('😃'); console.log(utf8ThenBase64); // Go ahead, try "Decoding" this alien message with your human tools.

Using encodeURIComponent() forces the string into the range of byte values that btoa() can handle. Remember, JavaScript doesn't like when you force an out-of-range character on btoa()!

Browser support

Not all browsers may support btoa(). A quick check at caniuse.com might just save your day.

There are also polyfills available for older browsers, like Internet Explorer. Plus, jQuery offers a jquery-base64 plugin that can help you encode and decode Base64 in IE9 and lower.

And for those brave souls working on IE7, remember to replace "this" with "Base64" when using btoa().

Handling binary data

You might find yourself needing to encode binary data to Base64.

First, you need to convert the binary data into a byte array before passing it to btoa(). Here's an example:

function binDataToBase64(binData) { let binary = ''; let bytes = new Uint8Array(binData); let len = bytes.byteLength; for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); }

This allows btoa() to correctly process the binary data. You can load the binary data using XMLHttpRequest or other ways like the fetch API.

Node.js alternative

If you're in the comfy world of Node.js, the Buffer class is your best friend for Base64 operations.

let base64 = Buffer.from('Victory is mine!').toString('base64'); console.log(base64); // Now only if Node.js could make me a cup of tea...

Play nice with libraries and frameworks

Angular-base64 is a nice tool to add to your Angular armory for Base64 encoding and decoding. If you're using Dojo.js, the dojox.encoding.base64 library should serve you well.

Handling errors

Handling exceptions is crucial when dealing with encoding and decoding to Base64.

try { let base64 = btoa('😃'); } catch (e) { console.error('Instructions unclear, disk stuck in toaster.', e); }

This cute little try-catch block could save your code from sudden death.

Further reading

Dive deeper with the references given below. Run tests with a variety of data to cover different edge cases. Put your new Base64 skills to the test!