JavaScript计算字符串中每个字符出现的次数

字符串中字符计数的实现
本文介绍了一种使用JavaScript实现的字符串中字符计数的方法,并提供了完整的代码示例。该方法通过正则表达式去除特定字符并统计剩余字符的数量。

代码如下:

function numInstring(str){
str=str.replace(/ /ig,"");
var strArr=str.split("");
var result=[],beforeLength,afterLength,reg;
for(var i=0;i<strArr.length;i++){
if(str.indexOf(strArr[i])!=-1){
beforeLength=str.length;
reg=new RegExp(strArr[i],"ig");
str=str.replace(reg,"");
afterLength=str.length;
result.push(strArr[i]+":"+(beforeLength-afterLength));
}
}
return result;
}

var result=numInstring("This section of the site is dedicated to the JavaScript language itself, the parts that are not specific to Web pages or other host");

console.log(result);

/*result:
["T:17", "h:7", "i:9", "s:10", "e:14", "c:5", "o:8", "n:3", "f:3", "d:3", "a:9", "J:1", "v:1", "r:5", "p:4", "l:2", "g:3", "u:1", ",:1", "W:1", "b:1"]
*/

其他方法:http://www.cnblogs.com/wyflogo/archive/2012/02/26/2368515.html




本文转自Artwl博客园博客,原文链接:http://www.cnblogs.com/artwl/,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值