How to useBase64 Encoding and Decoding in Javascript
Convert the byte array to a Base64 string using `btoa` after converting each byte to a character. Then, decode the Base64 string back to a normal string using `atob`. This method effectively handles the conversion via an intermediate Base64 representation.
Example: The byteArrayToBase64 function converts a byte array to Base64 string using btoa, and base64ToString converts a Base64 string back to the original string using atob
function byteArrayToBase64(byteArray) {
return btoa(String.fromCharCode.apply(null, byteArray));
}
function base64ToString(base64) {
return atob(base64);
}
const byteArray = [72, 101, 108, 108, 111];
const base64String = byteArrayToBase64(byteArray);
console.log(base64ToString(base64String));
Output
Hello
How to Convert Byte Array to String in JavaScript ?
A Byte array is an array containing encoded data in the form of unsigned integers. It can’t be used directly. We have to decode it to get the meaning full data out of it. In this article, we will learn the conversion of a given byte array to a string of characters.
Various approaches to convert byte array to string are as follows:
Table of Content
- Using WebAPI TextDecoder.decode() Method
- Using Buffer and toString() Methods
- Using JavaScript string.fromCharCode() Method
- Using Base64 Encoding and Decoding
- Using TextDecoder.decode() with Node.js Buffer
- Using the String constructor with Array.join