Home > Article > Web Front-end > How to get characters that appear multiple times in a string in JavaScript (code)
The content of this article is about how JavaScript can obtain characters (codes) that appear multiple times in a string. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I am a person who is not very good at expressing myself, so I try my best to use code to explain my understanding and thinking. Without further ado, I will just post the code:
fuction getStingMax(str){ if(typeof str !== "string"){ alert("请传入string类型的数据") return } let countObj ={},max=[{key:str[0],num:1}]; for(let i=0;i<a.length;i++){ let char=str[i]; countObj[char]=countObj[char]?countObj[char]+1:1; } for(let chart in countObj){ if(max[0].num<countObj[char]){ max=[]; max[0]={key:char,num:countObj[char]} }else if(max[0].num===countObj[char]){ max.push({key:char,num:b[char]}) } } console.log(max); return { max:max } }
In this code, I first performed a parameter check to ensure that the incoming string was a string. Then the str passed in from the outside is counted, and the counting result is placed in countObj. Then traverse each attribute of countObj, find the string collection with the most occurrences, store it in the max array, and print out the max array. Finally, the max array will be returned in the max attribute of the returned object (returning with an object is to facilitate the future expansion of this method).
The above is the detailed content of How to get characters that appear multiple times in a string in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!