Reputation: 89
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
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
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
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