

To convert a binary string into its corresponding character(s) in JavaScript, the following steps can be taken:


Split the binary string: If the binary string represents multiple characters (e.g., "01000001 01100010" for "Ab"), it needs to be split into individual binary representations of each character. This is typically done by splitting the string by a delimiter, usually a space.

    const binaryString = "01000001 01100010"; // Binary for "Ab"
    const binaryArray = binaryString.split(" ");
    // binaryArray will be ["01000001", "01100010"]
    
    Convert each binary segment to its decimal (ASCII/Unicode) equivalent: Each binary segment (representing a single character) needs to be converted into its decimal integer value. The parseInt() function with a radix of 2 is used for this purpose.
    
        const decimalValue = parseInt("01000001", 2);
    // decimalValue will be 65 (ASCII for 'A')
    
    Convert the decimal value to its character representation: The String.fromCharCode() method is used to convert the decimal (ASCII or Unicode) value into its corresponding character.
    
        const character = String.fromCharCode(65);
    // character will be 'A'
    
    Combine the characters: If multiple characters are being converted, the individual characters can be joined together to form a complete string.
    
       const resultString = binaryArray.map(binary => String.fromCharCode(parseInt(binary, 2))).join("");
    // resultString will be "Ab"
    
    Example Function:
JavaScript

function binaryToText(binaryString) {
  // Split the binary string into an array of individual binary character representations
  const binaryArray = binaryString.split(" ");

  // Map each binary string to its corresponding character
  const characters = binaryArray.map(binary => {
    // Convert the binary string to an integer (base 2)
    const decimalValue = parseInt(binary, 2);
    // Convert the integer to its corresponding character
    return String.fromCharCode(decimalValue);
  });

  // Join the array of characters back into a single string
  return characters.join("");
}

const binaryInput = "01001000 01100101 01101100 01101100 01101111"; // "Hello"
const convertedText = binaryToText(binaryInput);
console.log(convertedText); // Output: Hello

