function toGetTheMostCharsByArray(s) {
var r = {};
for(var i = 0;i < s.length;i++) {
if(!r[s[i]]) {
r[s[i]] = 1;
} else {
r[s[i]]++;
}
}
var max = {
"value " :s[0],
"num" : r[s[0]]
};
for(var n in r) {//对象使用in关键字,因为没有length
if(r[n] > max.num) {
max.num = r[n];
max.value = n;
}
}
return max;
}
function toGetTheMostCharsByRegex(s) {
var a = s.split('');
a.sort();
s = a.join('');
var regex = /(\w)\1+/g ;//\1代表重复的
var max = {
"value " :s[0],
"num" : 0
};
s.replace(regex,function(a,b) {
if(max.num < a.length) {
max.num = a.length;
max.value = b;
}
});
return max;
}
var test = "efdfssssfrhth";
console.info("使用常规方法 ,出现最多的字符串为:"+toGetTheMostCharsByArray(test).value+" ,出现次数:"+toGetTheMostCharsByArray(test).num);
console.info("使用字符串匹配,出现最多的字符串为:"+toGetTheMostCharsByRegex(test).value+" ,出现次数:"+toGetTheMostCharsByRegex(test).num);
10-15
183
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-26
1570
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-24
2192
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)