1

I am having trouble with a specific peice of javascript. my code should find a specific letter in the textarea, chosen and writen by a person. I need help counting my specific characters.

function search(){

    var s= document.getElementById("find").value;
    document.getElementById("letter").value= s;

    var t= document.getElementById("text");
    var c= document.getElementById("find").text;
}

(this is my current code)

  • Possible duplicate of [Count the number of occurrences of a character in a string in Javascript](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript) – niceman May 24 '17 at 08:55

2 Answers2

2

You can convert the ids of html element as per your need.

HTML :-

function search(){

    var textareaValue = document.getElementById("text").value;
    //console.log(textareaValue);
    
    var characterToSearch = document.getElementById("characterToFind").value;
    //console.log(characterToSearch);
    var count = 0;
    for(var i = 0; i < textareaValue.length; i++){
     if(characterToSearch == textareaValue[i]){
       count++;
      }
    }
    document.getElementById("totalCharacters").innerHTML = count;
    /*
    document.getElementById("letter").value= s;

    var t= document.getElementById("text");
    var c= document.getElementById("find").text;
    */
}
<label>Textarea</label> <textarea id="text">
</textarea>
<br>
<label>Enter character to find</label>
<input type="text" id="characterToFind">
<br>
<input type="button" onclick="search();" value="Search">
<br>
<label>Characters Found : </label><label id="totalCharacters"></label>
Lalit
  • 1,354
  • 1
  • 8
  • 13
1

I've used RegExp for things like this in the past, it's probably not the most performant solution though:

var charCount = (text.match(RegExp(letter, "g")) || []).length;

You should also validate that it's actually a letter being searched for, otherwise you'll have to escape characters that are control characters in RegExp

Lennholm
  • 7,205
  • 1
  • 21
  • 30