How can you encode a string to Base64 in JavaScript?
To encode a string to Base64 in JavaScript, simply call btoa()
:
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.
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:
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.
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.
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!
Was this article helpful?