Count repeated letters in a string

前端 未结 7 1957
耶瑟儿~
耶瑟儿~ 2021-01-06 02:06

I\'m stuck with the following problem: I need to find repeated characters in a string. Basically what I want is regular expression that will match like that



        
7条回答
  •  梦毁少年i
    2021-01-06 02:25

    You can use

    ([a-zA-Z]).*(\1)
    

    Demo regex


    Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:

    Build an associative array with the count of the characters in the string:

    var obj={}
    var repeats=[];
    str='banana'
    
    for(x = 0, length = str.length; x < length; x++) {
        var l = str.charAt(x)
        obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
    }
    
    console.log(obj)
    

    Prints

    { b: 1, a: 3, n: 2 }
    

    Then build an array of your specifications:

    for (var key in obj) {
        if (obj.hasOwnProperty(key) && obj[key]>1) {
            repeats.push(new Array( obj[key]+ 1 ).join( key ));
        }
    }
    console.log(repeats)
    

    Prints:

    [ 'aaa', 'nn' ]
    

提交回复
热议问题