Learning Center
JavaScript

How to Encode and Decode Strings Using Base64 in JavaScript

12 Feb 2025
Hostman Team
Hostman Team

In modern web development, Base64 encoding plays a significant role in data exchange between clients and servers. This method allows converting binary data into string format, which is particularly useful for transmitting images, files, and other information in text or JSON format.

In this guide, we will explore methods for encoding and decoding strings using Base64 in JavaScript, as well as share real-world examples and practical recommendations for applying this technique.

What is Base64, and Why is It Useful?
Copy link

The Base64 encoding algorithm is a method of transforming binary data into an ASCII string format. This is achieved by dividing the original data into 6-bit blocks and replacing each block with a corresponding character from a predefined set.

The main advantages of Base64 encoding include:

  • Enabling the transmission of binary data over text-based protocols such as HTTP or JSON.
  • Preventing issues related to incorrect handling of binary characters.
  • Easy integration with various programming languages and systems.

Base64 Encoding Algorithm
Copy link

The Base64 encoding method works as follows:

  1. The original binary data is divided into 3-byte (24-bit) blocks.
  2. Each 3-byte block is split into 4 blocks of 6 bits.
  3. Each 6-bit value is replaced by a corresponding character from the Base64 table.
  4. If the original data length is not a multiple of 3, = characters are added to make the resulting string length a multiple of 4.

Encoding and Decoding Methods in JavaScript
Copy link

JavaScript provides built-in functions for working with Base64 and third-party libraries that offer extended functionality.

Encoding a String to Base64
Copy link

To encode a string to Base64 in JavaScript, the btoa() function is used. This function takes a string, encodes it in Base64, and returns the result:

const originalString = "Hostman";
const encodedString = btoa(originalString);
console.log(encodedString); // Outputs the encoded string

This example demonstrates converting text to Base64 format. The built-in btoa() method is applied to the original value "Hostman", stored in the constant originalString. After processing, the result is stored in the encodedString variable and then displayed in the console as "SG9zdG1hbg==".

This encoding method works efficiently with text containing basic ASCII characters but does not support Unicode. The transformation mechanism uses a special set of characters consisting of Latin alphabet letters, numbers, and two additional symbols: a plus (+) and a slash (/).

Image1

Unicode String Encoding
Copy link

function encodeBase64Unicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

const originalString = "Hostman 🚀";
const encodedString = encodeBase64Unicode(originalString);
console.log(encodedString);

As we can see in this example, the encodeBase64Unicode function encodes a string to Base64 with support for Unicode. First, encodeURIComponent is used, and then a regular expression converts the encoded characters using String.fromCharCode. Finally, btoa is applied.

In this example, the string "Hostman 🚀" is encoded, and the result "SG9zdG1hbiDwn5qA" appears in the console. This method is necessary for correctly handling text containing Unicode characters, as the standard btoa() function cannot process them.

Image2

Decoding a String from Base64
Copy link

const encodedString = "SGVsbG8gV29ybGQ=";

function decodeBase64Unicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + c.charCodeAt(0).toString(16).padStart(2, '0');
    }).join(''));
}

const decodedString = decodeBase64Unicode(encodedString);
console.log(decodedString);

As we can see, a variable encodedString is created containing a Base64-encoded string. The decodeBase64Unicode function decodes it by using Array.prototype.map and charCodeAt to convert it to Unicode. The result is stored in decodedString and displayed using console.log().

The console will display the message Hello World.

Image3

Online Tools for Base64 Encoding and Decoding
Copy link

Many online tools allow you to quickly encode and decode strings and files without the need to write your own code. Some popular tools include:

  • base64encode.org allows encoding and decoding of text and files.
  • CyberChef is a multifunctional tool for data processing, including Base64.
  • base64.guru provides detailed information and tools for working with Base64.

Advantages of using online tools:

  • Speed and convenience
  • Ability to work without installing software
  • Support for various data formats

And some disadvantages:

  • Data size limitations
  • Possible data privacy concerns

File Encoding and Decoding in Base64
Copy link

Encoding a file in Base64 allows you to embed binary files, such as images or documents, directly into text formats like JSON or HTML. In JavaScript, this is done using the FileReader object.

Example of encoding an image to Base64:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Base64 Image Encoding</title>
</head>
<body>
    <input type="file" id="fileInput" accept="image/*">
    <img id="preview" src="" alt="Preview" />

    <script>
        document.getElementById('fileInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const base64String = e.target.result;
                    console.log(base64String);
                    document.getElementById('preview').src = base64String;
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>
</html>

Image4

As shown in this example, we create a form with an <input> element for selecting images and an <img> element for previewing the image. JavaScript adds a change event listener to the input. When we select a file, a FileReader object is created to read the file and output the result as a Base64 string to the console, setting it as the source for the <img> element.

In the screenshot, you can see an image with the Hostman logo, along with the Base64-encoded string displayed in the console after running the code.

Comparison of Different Base64 Encoding Methods
Copy link

Encoding Method

Description

Advantages

Disadvantages

btoa() and atob()

Built-in functions for encoding and decoding strings

Easy to use

Limited to ASCII characters

FileReader

Works with files for Base64 encoding and decoding

Can handle files

Asynchronous nature can complicate coding

Third-party Libraries

Libraries providing extended functionality

Additional features and UTF-8 support

Requires library inclusion

Online Tools

Web services for quick encoding and decoding

Fast and convenient

Limitations on data size and data privacy concerns

Conclusion
Copy link

Base64 encoding and decoding strings using JavaScript is a popular method for converting data that is widely used in web development. Base64 allows you to convert binary data into a string format, which is easy to transmit through text-based protocols such as HTTP or WebSocket.

The encoding algorithm splits data into 3-byte blocks and transforms them into four characters from a special alphabet. This ensures compatibility with systems that support only text content. Built-in JavaScript functions like btoa() and atob() simplify encoding and decoding, though you may need additional logic using TextEncoder and TextDecoder to handle Unicode.