JavaScript specific character counting

325 Views Asked by At

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)

2

There are 2 best solutions below

0
On BEST ANSWER

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>

2
On

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