Use JS to get the most frequent letters in the string

Source: Internet
Author: User
Tags eval regular expression

There are such a topic on the Internet:

Quote:

A string string= "ADADFDFSEFFSERFEFSEFSEETSDG" to find the letters and occurrences of the highest number of occurrences.

The classic solution is to remove the first character (the first letter) of the string, and replace the string with a regular expression (the first character) instead of NULL, and the number of occurrences of the letter is the original string length minus the replacement string length. Loop iteration to find the longest letter of the length.

<script type="text/javascript">
//<![CDATA[
var str ="adadfdfseffserfefsefseeffffftsdg"; //命名一个变量放置给出的字符串
var maxLength = 0; //命名一个变量放置字母出现的最高次数并初始化为0
var result = ''; //命名一个变量放置结果输入
while( str != '' ){ //循环迭代开始,并判断字符串是否为空
  oldStr = str; //将原始的字符串变量赋值给新变量
  getStr = str.substr(0,1); //用字符串的substr的方法得到第一个字符(首字母)
  eval("str = str.replace(/"+getStr+"/g,'')"); //详细如补充
  if( oldStr.length-str.length > maxLength ) { //判断原始的字符串的长度减去替代后字符串长度是否大于之前出现的最大的字符串长度
maxLength = oldStr.length-str.length; //两字符串长度相减得到最大的字符串长度
result = getStr + "=" + maxLength //返回最大的字符串结果(字母、出现次数)
}
}
alert(result) //弹出结果
//]]>
</script>

Add:

eval ("str = str.replace (/" +getstr+ "/g, ')");

Many people may want to write str = str.replace (/getstr/g, ""), but the result is wrong. Why, in this sentence, the expression matches the Getstr string, not the first letter that the getstr points to. The Eval method avoids (first getstr gets the first letter, the string is concatenated with "str = str.replace (/" +getstr+ "/g,") "and finally executes the code in the Eval, which is: first explain the JavaScript code, And then execute it again).

PS: Pony pointed out that eval performance is not good, error prone, and poor readability. It is recommended that eval ("str = str.replace (/" +getstr+ "/g, ')" be changed to:

str = str.replace (new RegExp (Getstr, "G"), "")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.