JS: Character Counter


<script type="text/javascript">
var char_counter;
reset();

var cList = {
  "a" : 0,"b" : 1,"c" : 2,"d" : 3,"e" : 4,"f" : 5,
  "g" : 6,"h" : 7,"i" : 8,"j" : 9,"k" : 10,"l" : 11,
  "m" : 12,"n" : 13,"o" : 14,"p" : 15,"q" : 16,"r" : 17,
  "s" : 18,"t" : 19,"u" : 20,"v" : 21,"w" : 22,
  "x" : 23,"y" : 24,"z" : 25,
}

var cRevList = {
0  : "a",1  : "b",2  : "c",3  : "d",4  : "e",5  : "f",
6  : "g",7  : "h",8  : "i",9  : "j",10  : "k",11  : "l",
12  : "m",13  : "n",14  : "o",15  : "p",16  : "q",17  : "r",
18  : "s",19  : "t",20  : "u",21  : "v",22  : "w",
23  : "x",24  : "y",25  : "z",
}

function reset(){
char_counter = [];
for (i = 0;i < 26;i++){
  char_counter.push(0);
}
}

function add(char){
char_counter[cList[char]]++;
}

function count(){
  var out = document.getElementById("out");
  var txt = document.getElementById("text").value;
  txt = txt.toLowerCase();
  var outString = "";
  for (var i = 0; i < txt.length; i++) {
    add(txt.charAt(i));
  }
  for (i = 0;i < 26;i++){
    if (char_counter[i] > 0)outString += cRevList[i] + ":" + char_counter[i];
  }
  out.innerText = outString;
  reset();
}
</script>
<input type="text" id="text"><input type="button" value="Count Characters" onclick="count()">
<br><p id="out"></p>

Today, instead of the challenge I made a simple script to count characters in a string.

Leave a Comment