首页 > 代码库 > js实现从字符串中查找出现次数最多的字符的两种解决办法

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

方法一:正则表达式匹配

 

 1  var str = "adadfdfseffserfefsefseeffffftsdg"; 2         var maxLength = 0; var result = ""; 3         while (str != ‘‘) { 4             oldStr = str; 5             getStr = str.charAt(0); 6             str = str.replace(new RegExp(getStr, "g"), ""); 7             if (oldStr.length - str.length > maxLength) { 8                 maxLength = oldStr.length - str.length; 9                 result = getStr + "=" + maxLength;10             }11         } 12       alert(result);

方法二:利用数组存储

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