Introduction
In JavaScript, it is possible to use Base64 to encode and decode strings.
In this article, you will be introduced to the btoa and atob JavaScript functions that are available in modern web browsers.
Prerequisites
To follow along with this article, you will need:
An understanding of strings in JavaScript. You can consult How To Work with Strings in JavaScript to learn more.
An understanding of using functions available to the Window or WorkerGlobalScope.
An understanding of the Developer Console. You can consult How To Use the JavaScript Developer Console to learn more.
Encoding and Decoding base64 decode Strings with Base64
btoa() and atob() are two Base64 helper functions that are a core part of the HTML specification and available in all modern browsers.
Note: The naming of these functions reference old Unix commands for converting binary to ASCII (btoa) and ASCII to binary (atob). However, “both the input and output of these functions are Unicode strings”.
btoa() takes a string and encodes it to Base64.
Let’s say you have a string, “Hello World!”, and wish to encode it to Base64. In your browser’s web developer console, define the string, encode it, and display the encoded string:
// Define the string
var decodedStringBtoA = ‘Hello World!’;
// Encode the String
var encodedStringBtoA = btoa(decodedStringBtoA);
console.log(encodedStringBtoA);
The output of this code is a string of characters with letters and numbers:
Output
SGVsbG8gV29ybGQh
atob() takes a string and decodes it from Base64.
Let’s take the encoded string from earlier, ‘SGVsbG8gV29ybGQh’, and decode it from Base64. In your browser’s web developer console, define the string, decode it, and display the decoded string:
// Define the string
var encodedStringAtoB = ‘SGVsbG8gV29ybGQh’;
// Decode the String
var decodedStringAtoB = atob(encodedStringAtoB);
console.log(decodedStringAtoB);
The output of this code reveals the string has been converted back to its original message:
Output
Hello World!
Now, you have two tools for encoding and decoding Base64.
Leave a comment