js string to base64 code example
Example 1: nodejs string to base64
> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World
Example 2: javascript base64 encode
var string = "Hello folks how are you doing today?";
var encodedString = btoa(string);
var decodedString = atob(encodedString);
Example 3: javascript encode base64
const encoded = window.btoa('Alireza Dezfoolian');
const decoded = window.atob(encoded);
Example 4: javascript base64 decode
var decodedString = atob(encodedString);
Example 5: javascript base64url decode
var decode = function(input) {
input = input
.replace(/-/g, '+')
.replace(/_/g, '/');
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;
}