Use JS to get the most occurrences of the letter _javascript tips in the string

Source: Internet
Author: User
Tags eval
<script type= "Text/javascript" > var str = "ADADFDFSEFFSERFEFSEFSEEFFFFFTSDG"; Name a variable to place the given string var maxLength = 0; Name a variable to place the highest number of letters appearing and initialize to 0 var result = '; Name a variable drop result input while (str!= ') {//loop iteration start, and determine whether the string is empty oldstr = str;//Assign the original string variable to the new variable getstr = STR.SUBSTR (0 , 1); Gets the first character (first letter) eval ("str = str.replace (/" +getstr+ "/g, ')" by the Substr method of the string); Details such as supplemental if (Oldstr.length-str.length > MaxLength) {//Determine the length of the original string minus whether the replacement string length is greater than the maximum length of the string before it appears maxlengt h = oldstr.length-str.length; Double string length subtraction get maximum string length result = getstr + "=" + maxLength//return maximum string results (Letters, occurrences)} alert (Result)//Popup results </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Add:
Copy Code code as follows:

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

Many people may want to write str = str.replace (/getstr/g, "), but the result is a mistake. 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).

Eval performance is bad, error prone, and not readable. 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.