Write a JavaScript Program to Encode a String to Base64

Base64 encoding is a way to represent binary data in a textual format.

It’s often used for transmitting data over the internet or storing data in a database.

In JavaScript, we can easily encode a string to Base64 using the built-in btoa() function.

The btoa() function takes a string as its argument and returns a Base64-encoded string. Here’s an example:

const myString = "Hello, world!";
const encodedString = btoa(myString);
console.log(encodedString); // "SGVsbG8sIHdvcmxkIQ=="

In this example, we start with the string “Hello, world!”. We then pass that string to the btoa() function to get the Base64-encoded string “SGVsbG8sIHdvcmxkIQ==”.

It’s important to note that the btoa() function only works with ASCII characters.

If you need to encode a string that contains non-ASCII characters, you’ll need to use a different method, such as the TextEncoder API.

Here’s an example:

const myString = "こんにちは、世界!";
const encoder = new TextEncoder();
const data = encoder.encode(myString);
const encodedString = btoa(String.fromCharCode(…new Uint8Array(data)));
console.log(encodedString); // "44GC44GE44GG44Gv44CB44Kr44Gr44Gh77yI"

In this example, we start with the string “こんにちは、世界!”, which contains non-ASCII characters.

We then create a TextEncoder object and use it to encode the string to a Uint8Array object.

We then convert the Uint8Array object to a string and pass it to the btoa() function to get the Base64-encoded string “44GC44GE44GG44Gv44CB44Kr44Gr44Gh77yI”.

In conclusion, encoding a string to Base64 in JavaScript is a simple task that can be accomplished using the built-in btoa() function.

However, if your string contains non-ASCII characters, you’ll need to use a different method, such as the TextEncoder API.