-2

I'm trying to write a function that works like

"aaaabbccccdeeeaaaaa" --> "abcdea"

but I can't figure out how to actually remove characters from the string. So where I'm at is

String.prototype.removeConsecutives = function()
{
      let k = 0;
    for(int i = 0; i < this.length; ++i)
        if(this[i] !== this[i-1])
          this[k++] = this[i];
    // now I want to remove the characters in the range
    // of indices [k, this.length)
}
user6048670
  • 2,861
  • 4
  • 16
  • 20

1 Answers1

2

This is easy with a regex replace:

var result = "aaaabbccccdeeeaaaaa".replace(/(.)\1+/g,"$1");

console.log(result);

In the regex I've shown, (.) matches any character, and then \1 is a back-reference to whatever matched in the parentheses with + meaning one or more of those. Do a global replace with the g flag. And the replacement string uses $1 to use the sub-match in parentheses.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241