encode and decode a string in javascript

To encode a string in JavaScript, you can use the btoa() function which stands for "binary to ASCII":

index.tsx
const stringToEncode = 'hello world';
const encodedString = btoa(stringToEncode);
82 chars
3 lines

The btoa() function converts the plain string to base64 encoding. The encodedString variable will now contain the encoded string.

To decode a string in JavaScript, you can use the atob() function which stands for "ASCII to binary":

index.tsx
const encodedString = 'aGVsbG8gd29ybGQ=';
const stringToDecode = atob(encodedString);
86 chars
3 lines

The atob() function converts the base64-encoded string back to its original form. The stringToDecode variable will now contain the decoded string.

gistlibby LogSnag