var str = "abdcadfasfdbadfafdasdfasyweroweurowqrewqrwqrebwqrewqrejwq;;"; // console.log(numInstring(str)); function numInstring(str) {
var text = "";
//循环的套出每个字符出现的次数 str会慢慢的变短直到为空
while (str != "") {
//先将字符打散
var newstr = str.split("");
var count = ;
//求得第一个字符出现的次数
for (var i = ; i < newstr.length; i++) {
if (newstr[] == newstr[i]) {
count++;
}
}
//在字符串中删掉跟第一个字符一样的所有字符
var re = new RegExp(newstr[], "g");
str = str.replace(re, "");
text += newstr[] + ":" + count + "次;";
}
return text; //我这里返回的是一段文本 可以自己改写成自己想要的形式
}
方法二:
var str = "adadseffouyangpingfsffffftsdg";
(function(str) {
var t = str,
result = {};
while (t) { // if this l exists
var _st = t.substr(, );
var m = t.replace(new RegExp(_st, 'gi'), '');
result[_st] = t.length - m.length;
t = m;
}
var name;
for (name in result) {
document.write(name + ":" + result[name] + " ");
}
return result;
})(str);
统计字符串中出现次数最多的字符,并计算个数:
var str1 = "caibaojian.com";
var arr = str1.split("");
var obj = {};
var objArr = [];
for (var i = , j; j = arr[i]; i++) {
if (!obj[j]) {
obj[j] = ;
}
objArr[++obj[j]] = j;
}
console.info(objArr[objArr.length - ], objArr.length - );