View Full Version : Question regarding charCodeat for conversion

12-04-2012, 07:13 AM
So, I am quite the beginner at javascript and, for an assignment, I need to convert text to ascii. My professor mentioned charCodeat with using a for loop and an array, but I'm not sure how to do that. What my ultimate goal is to turn that ascii into binary and then the binary to morse code to use as a beat for a song. Here's what I have so far, but I think I'm way wrong. I think my problem is just trying to incorporate the charCodeat with the rest of the code. Any help?


I looked around and he said that I should do something like this:

<title>JavaScript String charCodeAt() Method</title>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1));
document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2));
document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3));
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4));
document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5));

Philip M
12-04-2012, 09:48 AM
No need to be over-elaborate.

INPUT <input type = "text" id = "inp" size = "80" onblur = "change2ASCII(this)">
ASCII RESULT <input type = "text" id = "res" size = "80">
ASCII TO BINARY RESULT <input type = "text" id = "bin" size = "80">

<script type = "text/javascript">
function change2ASCII(which) {
var val = which.value;
var result = [];
var binary = [];
for (var i=0; i<val.length; i++) {
var x = val.charCodeAt(i);
binary[i] = x.toString(2);
result[i] = x + " ";

document.getElementById("res").value = result.join(" ");
document.getElementById("bin").value = binary.join(" ");


You define an array either with var arrName = new Array()
or (preferred) var arrName = [];

Your professor should be aware that document.write() is in effect obsolete. document.write() statements must be run before the page finishes loading. Any document.write() statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page (including the Javascript which called it). So document.write() is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded. So useable only if the character string to be converted is pre-defined.

BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.

"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)