w3resource

JavaScript: Create a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data

JavaScript fundamental (ES6 Syntax): Exercise-262 with Solution

Encode String to Base-64

Write a JavaScript program to create a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

  • Create a Buffer for the given string with binary encoding and use Buffer.toString('base64') to return the encoded string.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function 'btoa' to encode a string to base64
const btoa = str => new Buffer(str, 'binary').toString('base64');

// Encode the string 'foobar' to base64
console.log(btoa('foobar'));

Flowchart:

flowchart: Create a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that encodes a string to Base-64 using btoa() in the browser.
  • Write a JavaScript function that converts a given string into its Base-64 encoded equivalent and logs the output.
  • Write a JavaScript program that handles Unicode characters during Base-64 encoding by first converting to UTF-8.
  • Write a JavaScript function that encodes and then decodes a string using Base-64 to verify data integrity.

Go to:


PREV : Check Page Bottom Visible.
NEXT : Capitalize First Letter.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.