Home > Web Front-end > JS Tutorial > How to get characters that appear multiple times in a string in JavaScript (code)

How to get characters that appear multiple times in a string in JavaScript (code)

不言
Release: 2019-03-13 13:38:14
forward
2358 people have browsed it

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
     }
}
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template