Employing TextEncoder and Byte Conversion
This strategy leverages the TextEncoder API, which encodes strings into bytes and then transforms these bytes into binary representation.
- Text Encoding: Employing the TextEncoder API, we’ll encode the input string into a sequence of bytes. This process effectively converts characters into their respective byte values.
- Byte-to-Binary Conversion: Subsequently, each byte is transformed into binary using the toString(2) method. This step ensures that each byte’s binary representation spans 8 bits consistently.
- Aggregation: The resulting binary values are combined, with spaces as separators, to compose the comprehensive binary representation of the input string.
Example: This example shows the use of the above-explained approach.
async function convertToBinaryApproach3(input) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(input);
const binaryResult =
[...encodedData].map(byte => byte.toString(2)
.padStart(8, '0')).join(' ');
return binaryResult;
}
const inputString = "GFG";
convertToBinaryApproach3(inputString)
.then(binaryRepresentation => {
console.log(binaryRepresentation);
})
.catch(error => {
console.error(error);
});
Output
01000111 01000110 01000111
JavaScript Program to Convert a String to Binary
In this article, we will learn how to convert a string to binary in JavaScript. Binary representation holds special importance, especially in the realms of cryptography, low-level tasks, and other diverse programming situations.
Below are the following approaches to convert a string to binary in JavaScript:
Table of Content
- Using String’s Character Codes and Bitwise Operators
- Leveraging Unicode Code Points and Conversion Methods
- Approach 3: Employing TextEncoder and Byte Conversion
- Approach 4: Using Array.from() and charCodeAt()