js实现从字符串中查找出现次数最多的字符的两种解决办法

时间:2024-07-30 10:03:14

方法一:正则表达式匹配

  var str = "adadfdfseffserfefsefseeffffftsdg";
var maxLength = ; var result = "";
while (str != '') {
oldStr = str;
getStr = str.charAt();
str = str.replace(new RegExp(getStr, "g"), "");
if (oldStr.length - str.length > maxLength) {
maxLength = oldStr.length - str.length;
result = getStr + "=" + maxLength;
}
}
alert(result);

方法二:利用数组存储

       var str = "abaacabbabab";
var tempStr = "";
var arr = Array;
arr = [];
for (var i = ; i < str.length - ; i++) { tempStr = str.charAt(i); if (str.split(tempStr).length > arr[]) { arr[] = str.split(tempStr).length - ; //储存该字符出现次数 arr[] = tempStr; //储存该字符
}
} alert(arr);