如何在JavaScript中删除部分字符串?

时间:2016-07-19 05:03:44

标签: javascript algorithm

我正在尝试编写一个像

一样的函数

"aaaabbccccdeeeaaaaa" - > "abcdea"

但我无法弄清楚如何从字符串中删除字符。所以我在哪里

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)
}

1 个答案:

答案 0 :(得分:2)

使用正则表达式替换很容易:

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

console.log(result);

在我显示的正则表达式中,(.)匹配任何字符,然后\1是对括号中匹配的任何内容的反向引用,+表示其中一个或多个。使用g标志进行全局替换。替换字符串使用$1来使用括号中的子匹配。