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?
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?
Share Improve this question edited May 23, 2017 at 10:30 CommunityBot 11 silver badge asked Feb 3, 2014 at 19:26 kazuokazuo 2971 gold badge6 silver badges15 bronze badges 2- 2 Don't use a regex too plicated for you to debug it. "Now you have two problems." – djechlin Commented Feb 3, 2014 at 19:27
- 2 This should not be downvoted. It's a legitimate question with a clear use-case. Furthermore, OP clearly put some thought/work into the problem. What in the world is going on with SO? It's turning into Reddit. – David Titarenco Commented Feb 3, 2014 at 19:30
2 Answers
Reset to default 7Try
"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.
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:
- match an instances of an individual character repeated at least one -
(.)\1{2,}
- then it will pass the match and the first substring into a callback function -
function(match, p1)
- 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()
.