hossein hayati
hossein hayati

Reputation: 1158

Remove consecutive duplicate characters in a string javascript

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 and etc
but there are not what I want as I described above.

actually, I used here for my purpose but something is wrong.

here is my code :

var str='11222_12_111_122_542_1212333_122';
var result = str.replace(/(1{2,}|2{2,}|3{2,}|4{2,}|5{2,}|6{2,}|7{2,}|8{2,}|9{2,})/g,'$1');
console.log(result);

and it is not working. it gives me the exact input in output.

as I mentioned above I have some string like 11122_11255_12_223_12 and the output I wish to have is this: 12_125_12_23_12, it means between the underlines is a number, and for each number if there are two or more digits next to each other(ex:223 has two 2), I want to keep just one of them.
thanks.

Upvotes: 11

Views: 9961

Answers (5)

Ravi Shekhar
Ravi Shekhar

Reputation: 21

function removeAdjacentDuplicates(str) {
    let newStr = '';
    for (let i = 0; i < str.length; i++) {
        if (str[i] !== str[i + 1])
            if (str[i - 1] !== str[i])
                newStr += str[i];
    }
    return newStr;
}

Upvotes: 1

Nitesh Vuppala
Nitesh Vuppala

Reputation: 47

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

Upvotes: 0

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

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)

Upvotes: 0

Danmoreng
Danmoreng

Reputation: 2367

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

Upvotes: 2

anubhava
anubhava

Reputation: 785058

You can use capture group and back-reference:

result = str.replace(/(.)\1+/g, '$1')

RegEx Demo

  • (.): Match any character and capture in group #1
  • \1+: Match 1+ characters same as in capture group #1

Upvotes: 29

Related Questions