JavaScript(JS) JS encode a string to base64

‮tth‬ps://www.theitroad.com

In JavaScript, you can encode a string to Base64 using the btoa() function. Here's an example:

const myString = 'Hello, world!';
const encodedString = btoa(myString);

console.log(encodedString); // Output: "SGVsbG8sIHdvcmxkIQ=="

In the above example, we first create a string myString. We then call the btoa() function with the myString variable as its argument, which encodes the string to Base64. The encoded string is then stored in the encodedString variable. Finally, we log the encodedString variable to the console, which displays the encoded string.

Note that the btoa() function only works with ASCII strings, so if your string contains non-ASCII characters, you will need to use a different encoding method. Also note that the atob() function can be used to decode a Base64-encoded string back to its original format.