Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count repeated letters in a string

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.

like image 550
Olena Horal Avatar asked May 28 '15 16:05

Olena Horal


1 Answers

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' ]
like image 182
dawg Avatar answered Sep 21 '22 12:09

dawg