

Then display the value of decodedStr variable inside the div_2 using myDiv_2.innerHTML property. Now to decode the above string into its original form you can use the atob() function and pass the encodedStr inside it. The string is not being converted into Base64. Let myDiv_2 = document.getElementById('div_2') Let myDiv_1 = document.getElementById('div_1') Then we will display the value of this variable inside the div_1 using myDiv_1.innerHTML property. We will store the result of this inside the encodedStr variable. For this, just pass the str variable as a parameter to this function. To encode this string, we will use the btoa() function. The string we will encode and decode in this example is Git stored inside the str variable. We are storing the references of these two div inside myDiv_1 and myDiv_2 using getElementById() method in JavaScript. In the below code, we have two div elements inside which we will display the encoded and decoded string. The btoa() takes a string and encodes it to Base64, and atob() takes an encoded string and decodes it. In JavaScript, we have two Base64 helper functions, btoa() and atob(), for converting a string into Base64 encoding and vice-versa. Encoding and Decoding a String to Base64 in JavaScript
#Javascript base64 encoding how to#
Let’s see how to encode and decode a string into Base64. Till now, what we have seen is just for understanding purposes. Now we don’t have to do all of this conversion manually.

#Javascript base64 encoding generator#
In the end, these decimal numbers are being converted into Base64 by following the Base64 encoding table.įinal Result: QR code generator in JavaScript These four binary segments are then converted into decimals. This 8-bit binary representation is then divided into four 6-bit segments. Then these ASCII values are converted into an 8-bit binary representation. To get a full list of ASCII values, visit this link. What just happened here is that the individual characters of the string are first represented into their ASCII value i.e, for capital G, its ASCII value is 71, for small i, its ASCII value is 105, and similarly for other characters as well. The Base64 encoding converts data into ASCII (American Standard Code for Information Interchange) format.įor Example, If you have a string Git, then in Base64 encoding format, this string will be represented as R29vZ2xl.

In total, there are 64 characters in this system, and therefore it is known as Base64. Get code examples like 'how to do base64 encoding in javascript' instantly right from your google search results with the Grepper Chrome Extension. The Base64 encoding character set consist of A-Z, a-z, 0-9, + and /.
