Javascript CharAt method doesnt work for a string

1.2k views Asked by At
var teksts= (document.getElementById("teksts").value);
letter=document.getElementById("letter").value;
var results = teksts.split(" ");
document.getElementById("1").innerHTML = results
var count = new Array
for(var i=0; i<results.length; i++)
      {
var first= new String (results[i])    
    for (var j=0; j<first.length; j++)
   {if (first.CharAt(j)==letter)
       {count [i]++}
      }

I have this piece of code in Javascript that is supposed to read a string from HTML and a letter and then find which one of the words has the most of this type of letters in it. So i tried to keep it simple, split the string into an array, have each of the array elements defined as a string and then have a loop go through every letter and if it is the letter that is asked for, mark it in count array.

The problem is, even though i specifically define that the word (in variable first) should be a string and then try to use CharAt method for it to get the specific symbol, i get an error "Uncaught TypeError: Object [object String] has no method 'CharAt' "

I can't with all my googling skills understand why the method won't work for me.

1

There are 1 answers

2
thefourtheye On BEST ANSWER
  1. The method name is charAt not CharAt, note the small c
  2. Suggestion 1: var count = new Array should have been var count = []; Its always better to create empty arrays like this, because Array can be anything at runtime as it can be overwritten.
  3. Suggestion 2: It is a good practice to mark the end of lines with ; (semi colon) in javascript.