1

Okay so I have seen a couple solutions to this problem however none of them are working for me. How do I convert text to binary with javascript?

function asciiConverter() {
  var output = '';
  var phrase =  document.getElementById('phrase').value;  
    phrase = phrase.split('');
    for (var i =0; i < phrase.length; i++) {
      output += 0 + phrase[i].charCodeAt(0).toString(2) + " ";
    } document.getElementById('ascii').innerHTML = output; 
}
<div id="converter">
      <h2>Type a phrase to be converted to binary via Ascii:</h2>
      <h3>Your phrase</h3>
      <textarea name="phrase" id="phrase" cols="50" rows="5" placeholder="Write your text here. . ." onkeyup="asciiConverter()"></textarea>
      <h3>Your phrase in Binary</h3>
      <input id="asciiButton" type="button" value="Convert!" onclick="asciiConverter()"/>
      <div id="ascii" ></div>

This works unless there are spaces or any special characters. I would like it to work with spaces and special characters. Any ideas?

1 Answer 1

1

Alrighty guys I figured it out! this way it will make sure it will always have the 00's it leaves off at the beginning!

function asciiConverter() {
  var code;
  var output = '';
  var phrase =  document.getElementById('phrase').value;  
    phrase = phrase.split('');
    for (var i =0; i < phrase.length; i++) {
      code = phrase[i].charCodeAt(0).toString(2);
      if (code.length !== 8) {
        code = '0' + code;
        if (code.length !== 8) {
          code = '0' + code;
        }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.