Alberto Moneti
Alberto Moneti

Reputation: 89

Character count in a textarea

I don't know how to create a jquery function that counts how many times a given character (for example the letter "b", lowcase) is repeated inside an element of the page (in my case a preformatted div).

Any suggestions?

Upvotes: 1

Views: 81

Answers (3)

mark_c
mark_c

Reputation: 1212

Reusable for any letter...

    function charCount (array, character) {
        // Keep a running total.
        var count = 0;
        // Loop over the array.
        for (var i = 0; i < array.length; i++) {
            // If the character matches, increment the count.
            if (array[i] === character) {
                count ++
            }
        }
        // Return the count when the loop has finished.
        return count;
    }

    // Push the characters into an array.
    var letterArray = $('.text').text().toLowerCase().split('');

    // Pass the array and chosen letter to the function
    alert(charCount( letterArray, 'b' )) // 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea class="text">Bubbles</textarea>

Upvotes: 2

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

A functional approach with lease line of code to send any character to search:-***

$(document).ready(function(){
  $('button').click(function(){
    console.log(getCharCount('b'));// send any character
  });
});

function getCharCount(search){
 return  $('textarea').val().toLowerCase().match(new RegExp(search, 'g')).length; // to check both lowercase case-uppercase presence
 //return ($('textarea').val().match(new RegExp(search, 'g')).length; // for lowercase match only
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

<button>count b</button>

Upvotes: 2

user7110739
user7110739

Reputation:

Do like below:-

$(document).ready(function(){
  $('button').click(function(){
     var countB = $('textarea').val().toUpperCase().match(/B/g); 
     if(countB){
      console.log(countB);
      console.log(countB.length);
     } 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

<button>count b</button>

Upvotes: 2

Related Questions