Remove consecutive duplicate characters in a string javascript

前端 未结 4 1114
臣服心动
臣服心动 2020-12-20 22:14

I have some string like 11122_11255_12_223_12 and the output I wish to have is this: 12_125_12_23_12
I already looked at this and also this a

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 22:42

    Easy and recursive way

    let x = "11122_11255_12_223_12".split('');
    let i = 0;
    let j = 1;
    
    function calc(x) {
      if (x[i] == x[j]) {
        x.splice(j, 1);
        calc(x);
      }
      
      if (j == x.length) {
        return x.join('');
      }
      
      i += 1;
      j += 1;
      calc(x);
    }
    console.log(calc(x));

提交回复
热议问题