string to base64 in javascript

How to Encode String to Base64 in JavaScript

It is important to keep your data in proper encoding format otherwise they will give error when you try to use them. Sometimes you may need to encode string to Base64 format using JavaScript. In this article, we will learn how to encode string to Base64 in JavaScript. You can also use these steps to convert an image or other data into Base64 format, where treat our input data as a string, before conversion.


How to Encode String to Base64 in JavaScript

Here are the steps to encode string to Base64 in JavaScript. You can easily convert string to Base64 and vice versa using btoa() and atob() functions respectively.

btoa() function accepts string and returns base64 encoding, whereas atob() accepts base64 encoded data and returns a string. Please note, while using btoa() if your string contains characters that cannot be converted into 8-bit format, it may give error. In such cases, you will need to encode it into byte array before passing it to btoa() function. When you use atob() it will return a string where each character is represented by 8-bit byte.

Here is a simple example to illustrate how these two functions work.

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

In this article, we have learnt how to encode string to base64. You can use it as a part of a bigger module or function to easily convert strings to & from Base64 formats.

Also read:

How to get Length of JavaScript Object
How to Get Client IP Address Using JavaScript
How to Break ForEach Loop in JavaScript
How to Validate Decimal Number in JavaScript
How to Fix Uncaught ReferenceError in jQuery

Leave a Reply

Your email address will not be published.