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
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>