jQuery gets the number of occurrences of a string

  • 2020-12-26 05:32:45
  • OfStack

Recommended reading: A tool for counting the number of occurrences of each string in jQuery

Without further ado, I will post the js code directly to you.


// Gets the number that appears most in the string and it 1 How many times 
var str = 'asdfssaaasasasasaa'; // Define string 
var json = {}; // Defines an array to store the number of characters per element 
for (var i = 0; i < str.length; i++) { // Iterate over all the elements in the string 
if (!json[str.charAt(i)]) { // Determines whether the current element already exists in the array  str.charAt(i)// The current element 
json[str.charAt(i)] = 1; // Assign a value to the number of elements in the corresponding array 
}
else 
{
json[str.charAt(i)]++; // Assign a value to the number of elements in an array 
}
};
var iMax = 0;// occurrences 
var iIndex = '';// The element name 
for(var i in json){ // The number and number of data that appear most frequently in reassignment 
if(json[i]>iMax){
iMax = json[i];
iIndex = i;
}
}
//alert(' The most frequent is :'+iIndex+' appear '+iMax+' time ');

The above code is the site to introduce jQuery to get the string of the most number, the code is simple and easy to understand, where you do not understand the welcome to leave a message, I will get in touch with you in time.


Related articles: