Count repeated letters in a string

前端 未结 7 1842
耶瑟儿~
耶瑟儿~ 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条回答
  • 2021-01-06 02:36

    More complicated than a RegExp solution, however it properly handles banana and assassin, where there are two overlapping groups of characters.

    This does make use of array.map, array.filter, and array.reduce, which means this exact solution doesn't support <=IE8, however it can be polyfilled quite easily.

    function findDuplicateCharacters(input) {
      // Split the string and count the occurrences of each character
      var count = input.split('').reduce(function(countMap, word) {
        countMap[word] = ++countMap[word] || 1;
        return countMap;
      }, {});
    
      // Get the letters that were found, and filter out any that only appear once.
      var matches = Object.keys(count)
        .filter(function (key) { return (count[key] > 1); })
        // Then map it and create a string with the correct length, filled with that letter.
        .map(function (key) {
          return new Array(count[key] + 1).join(key);
        });
    
      return matches;
    }
    
    var results = ['hello', 'here', 'happiness', 'pupil', 'banana'].map(findDuplicateCharacters);
    
    document.getElementById("results").innerHTML = results.join('<br />');
    <div id="results"></div>

    0 讨论(0)
提交回复
热议问题