我不知道如何创建一个jquery函数来计算给定字符(例如字母“b”,小写)在页面元素内重复的次数(在我的例子中是预格式化的div)。
有什么建议吗?
答案 0 :(得分:2)
一种功能性方法,使用租赁代码行发送任何字符进行搜索: - ***
$(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>
答案 1 :(得分:2)
如下所示: -
$(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>
答案 2 :(得分:2)
可以重复使用任何信件......
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
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea class="text">Bubbles</textarea>
&#13;