kazuo
kazuo

Reputation: 297

Javascript - remove repeating characters when there are more than 2 repeats

As what the title says. When there are more than 2 repeats of a letter in a string, the excess repeats are removed.

I have the following code based off this answer but it does not seem to work:

function removeRepeatingLetters (text) {
    return text.replace('^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$', '');
}

But it does not seem to work for my test string:

"bookkeepers! are amaazing! loooooooool"

The output for the sample string should be:

"bookkeepers! are amaazing! lool"

What am I doing wrong?

Upvotes: 1

Views: 2892

Answers (2)

Oriol
Oriol

Reputation: 288010

Try

"bookkeepers! are amaazing! loooooooool".replace(/(.)\1{2,}/g, '$1$1')
// "bookkeepers! are amaazing! lool"

The RegExp /(.)\1{2,}/ matches any single character followed by the same character two or more times.

The flag g ensures you match all occurrences.

Then, you replace each occurrence with the repeated character duplicated.

Note that the simpler .replace(/(.)\1+/g, '$1$1') should work too, but a bit slower because it does unnecessary replacements.

Upvotes: 7

talemyn
talemyn

Reputation: 7950

Another way (Oriol's answer works just fine) to do this is with a callback function:

function removeRepeatingLetters (text) {
    return text.replace(/(.)\1{2,}/g, function(match, p1) {
        return p1 + p1;
    });
}

This will:

  1. match an instances of an individual character repeated at least one - (.)\1{2,}
  2. then it will pass the match and the first substring into a callback function - function(match, p1)
  3. then it will return the first matched substring, appended to itself, as the value to replace the overall match - return p1 + p1;

Because of the g at the end of the regex, it will do it with all instances that it finds of repeated characters.

The above code works with the test string that you provided (along with a couple of others that I tested with ;) ). As mentioned, Oriol's works, but figured I'd share another option, since it gives you a glimpse into how to use the callback for .replace().

Upvotes: 1

Related Questions