Categories
JavaScript Answers

How to convert text to binary code in JavaScript?

Spread the love

Sometimes, we want to convert text to binary code in JavaScript.

In this article, we’ll look at how to convert text to binary code in JavaScript.

How to convert text to binary code in JavaScript?

To convert text to binary code in JavaScript, we use the charCodeAt method.

For instance, we write

const b = Array.from("abc")
  .map((each) => each.charCodeAt(0).toString(2))
  .join(" ");

to call Array.from with 'abc' to convert the string to an array of character strings.

Then we call map with a callback that returns the character code of the character string as a binary value with charCodeAt and toString as an array.

Next we call join to join the binary character code strings into 1 string with each value separated by a space.

Conclusion

To convert text to binary code in JavaScript, we use the charCodeAt method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *