base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

console.log(btoa("password")); // cGFzc3dvcmQ=

To decode, you can use the atob() function:

console.log(atob("cGFzc3dvcmQ=")); // password

From Angular 12 btoa() and atob() functions are deprecated. Use these instead:

console.log(Buffer.from("Hello World").toString('base64'));
// SGVsbG8gV29ybGQ=
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('binary'))
// Hello World

Note: you must explicit encoding!


For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2