String to binary in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as the only input. The function should construct and return the binary representation of the input string.

For example −

If the input string is −

const str = 'Hello World';

Then the output should be −

const output = '1001000 1100101 1101100 1101100 1101111 100000 1010111
1101111 1110010 1101100 1100100';

Example

The code for this will be −

const str = 'Hello World';
const textToBinary = (str = '') => {
   let res = '';
   res = str.split('').map(char => {
      return char.charCodeAt(0).toString(2);
   }).join(' ');
   return res;
};
console.log(textToBinary('Hello World'));

Output

And the output in the console will be −

1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100
raja
Published on 23-Nov-2020 11:11:55
Advertisements