Remove consecutive duplicate characters in a string javascript

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

    If you are intersted in a non-regex way, you can split the items on the _, and then map that by creating a Set of characters which will remove duplicates. Then you just join the data back together. Like this:

    var str = '11122_11255_12_223_12';
    let result = str
      // Split on the underscore
      .split('_')
      // map the list
      .map(i =>
        // Create a new set on each group of characters after we split again
        [...new Set(i.split(''))].join('')
      )
      // Convert the array back to a string
      .join('_')
    
    console.log(result)

提交回复
热议问题