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

AngularTypescriptNpm Install

Angular Problem Overview


How to encode or decode a string in angular 2 with base64 ??? My front-end tool is Angular 2. I had a password string, before passing it to API I need to base64 encode. Since in service base64 encoded string will be decoded.

So I am looking for some base64 encode/decode library for Angular2/Typescript and some options.

Thanks!!!

Angular Solutions


Solution 1 - Angular

Use the btoa() function to encode:

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

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

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

Solution 2 - Angular

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!

Solution 3 - Angular

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

Solution 4 - Angular

Use btoa("yourstring")

more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs

Solution 5 - Angular

Use btoa() for encode and atob() for decode

text_val:any="your encoding text";

Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0

Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpraveen kumarView Question on Stackoverflow
Solution 1 - AngularRobby CornelissenView Answer on Stackoverflow
Solution 2 - AngularEros MazzaView Answer on Stackoverflow
Solution 3 - AngularVIKAS KOHLIView Answer on Stackoverflow
Solution 4 - AngularshussonView Answer on Stackoverflow
Solution 5 - AngularYasinthaView Answer on Stackoverflow