There is a question on the Internet:
A string = "adadfdfseffserfefsefseetsdg" to find the most frequently used letters and the number of times.
The typical solution is to retrieve the first character (first letter) of a string, and replace the regular expression (first character) with the replacement of null, the number of occurrences of this letter is the original string length minus the replacement string length. Find the longest letter in the loop iteration.
<SCRIPT type = "text/JavaScript"> var STR = "adadadfdfseffserfefsefseeffffftsdg"; // name the string var maxlength = 0 given by a variable; // name the maximum number of times a variable is placed in a letter and initialized to 0var result = ''; // name a variable and enter the result while (STR! = '') {// Start of loop iteration, and judge whether the string is empty oldstr = STR; // assign the original string variable to the new variable getstr = Str. substr (); // obtain the first character (first letter) eval ("str = Str. replace (/"+ getstr +"/g, '')"); // If (oldstr. length-str.length> maxlength) {// determine the length of the original string minus whether the length of the string after replacement is greater than the maximum length of the previous string maxlength = oldstr. length-str.length; // two string lengths subtract to get the largest String Length result = getstr + "=" + maxlength // return the largest string result (letters, occurrences )}} alert (result) // the pop-up result </SCRIPT>
Supplement:
Eval ("str = Str. Replace (/" + getstr + "/g ,'')");
Many people may want to write STR = Str. Replace (/getstr/g, ") in this way, but the result is wrong. Why? In this sentence, the expression matches the getstr string instead of the first letter pointed to by getstr. The eval method can be used to avoid this problem (first, getstr gets the first letter to which it points, and uses a string to connect "str = Str. replace (/"+ getstr +"/g, ")", and finally execute this section in evalCode, That is, explain the JavaScript code first, and then execute it ).
Because of the poor eval performance, error-prone and poor readability. We recommend that you change eval ("STR = Str. Replace (/" + getstr + "/g,") ":
STR = Str. Replace (New Regexp (getstr, "G "),"")