我想计算一个字符出现在文本框中的次数..我完成了以下代码,但它只计算一个字符。想要计算每个角色。
<script>
$(document).ready(function(){
$("#sub").click(function(){
var str = $("#field").val();
alert(str.split('b').length-1);
});
});
</script>
<textarea id="field"></textarea>
<input type="submit" name="sub" id="sub" value="GO" />
如果我在textarea中键入'balab'意味着它将显示b-2 a-2 l-1
答案 0 :(得分:3)
试试这个:
var yourString = "balab";
var count = yourString.match(/b/g);
//b is your char, g is for searching all occurrences in the string
alert(count.length);
<强>更新强>
function printOccurence(string){
var unique=''; //unique chars
for(var i=0; i<string.length; i++){
if(string.lastIndexOf(string[i]) == string.indexOf(string[i])){
unique += string[i];
}
}
var occs=''; //result ex. 221
for(var i=0; i<unique.length; i++){
var re = new RegExp(unique[i], 'g');
var count = string.match(re);
occs = occs + count;
}
return occs;
}
答案 1 :(得分:0)
您可以遍历所有字母并获取每个字母的出现次数:
var all="abcdefghijklmnopqrstuvwxyz";
var str = $("#field").val();
for(var i=0; i<all.length; i++)
{
var char = all.charAt(i);
if(str.split(char).length>1)
console.log(char +"-"+ (str.split(char).length-1));
}
<强> Working Demo 强>
答案 2 :(得分:0)
按照以下代码运作
<html>
<head>
<script src='add jquery.js'></script>
<script>
var uniqueOccurence = "";
var str = $("#field").val();
for (var i = 0; i < str.length; i++) {
if(uniqueOccurence.indexOf(str.charAt(i)) < 0)
uniqueOccurence += str.charAt(i);
}
var text = "";
for (var i = 0; i < uniqueOccurence .length; i++) {
var char = uniqueOccurence .charAt(i);
if (str.split(char).length > 1) text +=+ char + str.split(char).length-1
}
$("#charNum").html(text);
</script>
</head>
<body>
<textarea id="field"></textarea>
<input type="submit" name="sub" id="sub" value="GO" />
<div id="charNum"></div>
</body>
</html>