;

How to Encode and Decode Strings With Base64 in Javascript


Tutorialsrack 19/05/2021 Jquery Javascript

In this article, you will learn how to encode and decode strings with base64 in javascript. We will use the btoa() method to encode the string and atob() method to decode the string. Both the functions are compatible with the modern web browser.

Here are the examples to encode and decode the string to base64 using javascript.

Example 1: Encode String to Base64 

The javascript btoa() function (stands for binary-to-ASCII) is used to create a Base64 encoded ASCII string from the binary data, where each character represents an 8-bit byte. This method accepts the binary string as an argument and returns a Base64 encoded ASCII string.

Example 1: Encode String to Base64 
// Function to encode a string to base64 format
function encode(str) {
    encodedString = btoa(str);
    return encodedString;
}

console.log("Encode String to Base64: " + encode("tutorials rack"));
//Output ==> "Encode String to Base64: dHV0b3JpYWxzIHJhY2s="

Example 2: Decode String From Base64

The javascript atob() function (stands for ASCII-to-binary) decodes a string from Base64 encoding, where each character represents an 8-bit byte. 

Example 2: Decode String From Base64
// Function to decode a string from base64 format
function decode(str) {
    decodedString = atob(str);
    return decodedString;
}

console.log("Decode String from Base64: " + decode("dHV0b3JpYWxzIHJhY2s="));
//Output ==> "Decode String from Base64: tutorials rack"

For more information on Base64 encoding and decoding, take a look at this MDN guide.

I hope this article will help you to understand how to encode and decode strings with base64 in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags