convert base64 javascript code example
Example 1: javascript base64 encode
var string = "Hello folks how are you doing today?";
var encodedString = btoa(string); // Base64 encode the String
var decodedString = atob(encodedString); // Base64 decode the String
Example 2: base64 to string and string to base64 javascript decode
// base64 to string
let base64ToString = Buffer.from(obj, "base64").toString();
base64ToString = JSON.parse(base64ToString);
//or
let str = 'bmltZXNoZGV1amEuY29t';
let buff = new Buffer(str, 'base64');
let base64ToStringNew = buff.toString('ascii');
// string to base64
let data = 'nimeshdeuja.com';
let buff = new Buffer(data);
let stringToBase64 = buff.toString('base64');
Example 3: javascript base64 decode
var decodedString = atob(encodedString);
Example 4: javascript base64url decode
var decode = function(input) {
// Replace non-url compatible chars with base64 standard chars
input = input
.replace(/-/g, '+')
.replace(/_/g, '/');
// Pad out with standard base64 required padding characters
var pad = input.length % 4;
if(pad) {
if(pad === 1) {
throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding');
}
input += new Array(5-pad).join('=');
}
return input;
}