var str = 'kkkkkkkskdksdsddsssssssasasdaaaaaaaaadsdssssssssss';
var mostCharacter = function (str) {
var result = {};
for (var i = 0; i < str.length; i++) {\
if (!result[str[i]]) {
result[str[i]] = 1;
}else{
result[str[i]] ++;
}
}
return JSON.stringify(result);
};
console.log(mostCharacter(str));
控制台输出:
{"k":9,"s":23,"d":7,"a":11}
另一种:
var str = 'kkkkkkkskdksdsddsssssssasasdaaaaaaaaadsdssssssssss';
var mostCharacter = function (str) {
str = str.split('').sort().join('');
var reg = /(\w)\1+/g;
var num =0;
var value = '';
var result = {};
var mostChar = 'mostChar';
str.replace(reg,function(ele,index){
if(ele.length > num){
num = ele.length
value = index;
}
result[index] = ele.length;
});
result[mostChar] = num;
return JSON.stringify(result);
};
console.log(mostCharacter(str));
控制台输出:
{"a":11,"d":7,"k":9,"s":23,"mostChar":23}