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.
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.
// 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="
The javascript atob()
function (stands for ASCII-to-binary) decodes a string from Base64 encoding, where each character represents an 8-bit byte.
// 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"
This works on almost all modern browsers such as Chrome, Firefox, Safari, Opera, and IE 10+.
Note: If a character exceeds the range of an 8-bit byte, i.e., Unicode character, btoa() will cause a Character Out Of Range exception. To fix this, the idea is to escape the whole string with UTF-8 and then encode it. Another proper way is to convert the UTF-16 string into a UTF-8 array of characters and then encode it.
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!
Comments