String to binary in JavaScript

Converting strings to binary representation is a common task in JavaScript programming. This involves converting each character to its ASCII code and then to binary format.

For example, if we have:

const str = 'Hello World';

The binary output should be:

1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

How It Works

The conversion process involves three steps:

  1. Split the string into individual characters
  2. Get the ASCII code of each character using charCodeAt()
  3. Convert each ASCII code to binary using toString(2)

Basic Implementation

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'));
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

Method 1: Using Array.from()

const stringToBinary = (str) => {
    return Array.from(str, char => char.charCodeAt(0).toString(2)).join(' ');
};

console.log(stringToBinary('Hello'));
console.log(stringToBinary('JavaScript'));
1001000 1100101 1101100 1101100 1101111
1001010 1100001 1110110 1100001 1010011 1100011 1110010 1101001 1110000 1110100

Method 2: Using for...of Loop

const convertToBinary = (text) => {
    let binary = [];
    
    for (const char of text) {
        binary.push(char.charCodeAt(0).toString(2));
    }
    
    return binary.join(' ');
};

console.log(convertToBinary('ABC'));
console.log(convertToBinary('123'));
1000001 1000010 1000011
110001 110010 110011

Padded Binary Format

For consistent 8-bit representation, you can pad with leading zeros:

const stringToPaddedBinary = (str) => {
    return str.split('').map(char => {
        return char.charCodeAt(0).toString(2).padStart(8, '0');
    }).join(' ');
};

console.log(stringToPaddedBinary('Hi'));
console.log(stringToPaddedBinary('123'));
01001000 01101001
00110001 00110010 00110011

Comparison

Method Performance Readability Features
Array.from() Good High Concise, functional
for...of Loop Best Medium Memory efficient
map() + split() Good High Chainable methods

Conclusion

Converting strings to binary in JavaScript is straightforward using charCodeAt() and toString(2). Use padStart() for consistent 8-bit formatting when needed.

Updated on: 2026-03-15T23:19:00+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements