一天一个js(6)找出字符串中出现次数最多的字符

此方法不能测试正则表达式用到的字符比如$^.?\等

 

http://blog.csdn.net/qmzmxfy/article/details/7431488

  1. <!DOCTYPE HTML>  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=gbk">  
  5. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>  
  6. <script type="text/javascript">  
  7. $(function(){  
  8.     $("input:button").click(function(){  
  9.         count();      
  10.     });  
  11. });  
  12. function count(){  
  13.     var str = $("input:text").val();//获取输入框中的值  
  14.     var maxlength = 0;//定义最大次数  
  15.     //循环:每次都获取字符串第一个字符,并将其替换为空,获取其个数。直到字符串为空  
  16.     while(str != ""){  
  17.         var oldstr = str;//给字符串定义新变量  
  18.         letter = str.substr(0,1);//使用substr方法获得字符串第一个字符  
  19.       var str = str.replace(new RegExp(letter,"g"),"");//使用正则表达式将字符串中“跟第一个字符相同的字符”替换为空  
  20.         //“oldstr.length - str.length”是当前字符的个数,判断其是否大于前一个字符的个数  
  21.         if(oldstr.length - str.length > maxlength){  
  22.             maxlength = oldstr.length - str.length;//将当前字符个数赋给变量maxlength  
  23.             $("span").text(letter);  
  24.             $("em").text(maxlength);  
  25.         };  
  26.     };  
  27. };  
  28. </script>  
  29. <style type="text/css">  
  30. span,em { color:#933; padding:0 5px;}  
  31. .text { width:500px;}  
  32. </style>  
  33. <title>找出字符串中出现次数最多的字符</title>  
  34. </head>  
  35.   
  36. <body>  
  37. <h2>输出一串字符,可以查找出字符串中出现次数最多的字符!</h2>  
  38. <input class="text" type="text" value="" />  
  39. <input type="button" value="查找" />  
  40. <p>出现最多的是:“<span>查找中...</span>”,共出现了<em>计算中...</em>次。</p>  
  41. </body>  
  42. </html>  



posted @ 2013-03-18 12:47  下里巴人or知己  阅读(241)  评论(0编辑  收藏  举报