base64 decide in javascript

In JavaScript, the btoa() and atob() functions can be used to encode and decode Base64-encoded strings, respectively.

The btoa() function encodes a given string using the Base64 encoding scheme. For example, to encode the string "Hello, World!" in Base64, you could do the following:

index.tsx
let encodedString = btoa("Hello, World!");
console.log(encodedString); // "SGVsbG8sIFdvcmxkIQ=="
97 chars
3 lines

The atob() function decodes a Base64-encoded string and returns the original string. For example, to decode the Base64-encoded string "SGVsbG8sIFdvcmxkIQ==", you could do the following:

index.tsx
let decodedString = atob("SGVsbG8sIFdvcmxkIQ==");
console.log(decodedString); // "Hello, World!"
97 chars
3 lines

Note that these functions only work with strings in ASCII format. To encode or decode a string with non-ASCII characters, you can use the TextEncoder and TextDecoder APIs.

index.tsx
let str = "こんにちは"; // Japanese greeting
let encoder = new TextEncoder();
let data = encoder.encode(str);
let base64 = btoa(String.fromCharCode.apply(null, data)); // Base64-encoded string
console.log(base64); // "44GC44GE44GG44Gq"
let decodedData = atob(base64).split('').map(function(c) { return c.charCodeAt(0); });
let decoder = new TextDecoder('utf-8');
let decodedStr = decoder.decode(new Uint8Array(decodedData));
console.log(decodedStr); // "こんにちは"
456 chars
10 lines

In the above example, the TextEncoder and TextDecoder APIs are used to convert the non-ASCII string into a format that can be encoded in Base64. The resulting Base64-encoded string is then decoded and converted back to the original non-ASCII string using the same APIs.

gistlibby LogSnag