Remove consecutive duplicate characters in a string javascript

前端 未结 4 1119
臣服心动
臣服心动 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

    I really like the regex solution. However, first thing which would come into my mind is a checking char by char with a loop:

    const str = "11122_11255_12_223_12";
    let last = "";
    let result = "";
    for(let i = 0; i < str.length; i++){
      let char = str.charAt(i);
      if(char !== last){
        result += char;
        last = char;
      }
    }
    console.log(result);

提交回复
热议问题