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
hello - ["ll"];
here - ["ee"];
happiness - ["pp","ss"];
pupil - ["pp"];
I have the one that matches consecutive repeated characters
/([a-z])\1+/g
Also the one that will match repeated chars and everything between them like this one
/([a-z])(?:.*)\1+/g
But cant figure out the correct one.
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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With