Encode String to Base64

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to encode a given string to base64 format using JavaScript. We will create a function that takes in a string, converts it to binary using a buffer, and then returns the base-64 encoded string. This lab aims to help learners understand the process of encoding data in base64 format and how it can be applied in real-world scenarios.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28285{{"`Encode String to Base64`"}} javascript/data_types -.-> lab-28285{{"`Encode String to Base64`"}} javascript/arith_ops -.-> lab-28285{{"`Encode String to Base64`"}} javascript/comp_ops -.-> lab-28285{{"`Encode String to Base64`"}} end

Encoding a String to Base64

To encode a String object to a base-64 encoded ASCII string, follow these steps:

  1. Open the Terminal/SSH and type node to start coding.
  2. Create a Buffer using the given string and the binary encoding.
  3. Use Buffer.prototype.toString() to return the base-64 encoded string.

Here's an example code snippet:

const encodeToBase64 = (str) => Buffer.from(str, "binary").toString("base64");

You can now use the encodeToBase64() function to encode any string to base-64. For example:

encodeToBase64("foobar"); // 'Zm9vYmFy'

Summary

Congratulations! You have completed the Encode String to Base64 lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like