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