How Can You Encode a String to Base64 in Javascript?

Base64 encoding is commonly used in JavaScript to convert data (such as strings or images) into a format that can be easily transmitted over the internet. In this article, we will explore different methods to encode a string to Base64 in JavaScript.

Method 1: Using the btoa() function

The simplest way to encode a string to Base64 in JavaScript is by using the built-in btoa() function. This function takes a string as input and returns the Base64 encoded string.

// String to be encoded
const str = "Hello, World!";

// Encoding the string to Base64
const encodedStr = btoa(str);

console.log(encodedStr);

The output of the above code will be:

SGVsbG8sIFdvcmxkIQ==

Method 2: Using the TextEncoder API

If you are working with modern browsers that support the TextEncoder API, you can use it to encode a string to Base64. This method provides better performance compared to the btoa() function.

// String to be encoded
const str = "Hello, World!";

// Encoding the string to Base64
const encoder = new TextEncoder();
const data = encoder.encode(str);
const base64Str = btoa(String.fromCharCode.apply(null, data));

console.log(base64Str);

The output of the above code will be the same as the previous method:

SGVsbG8sIFdvcmxkIQ==

Method 3: Using the Buffer object (Node.js)

If you are working with Node.js, you can use the Buffer object to encode a string to Base64. This method is specific to Node.js and is not available in browser-based JavaScript.

// String to be encoded
const str = "Hello, World!";

// Encoding the string to Base64
const buffer = Buffer.from(str, 'utf-8');
const base64Str = buffer.toString('base64');

console.log(base64Str);

The output of the above code will be the same as the previous methods:

SGVsbG8sIFdvcmxkIQ==

These are three different methods you can use to encode a string to Base64 in JavaScript. Choose the method that best suits your needs and enjoy the benefits of Base64 encoding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *