Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove consecutive duplicate characters using regex

Well i have following type of input and desired output.What i basically want to do is remove consecutively repeating characters.(Keep first character removed all the following consecutively repeating).

input = dup(["abracadabra","allottee","assessee"])
output = ["abracadabra","alote","asese"].

input = dup(["kelless","keenness"])
output =  ["keles","kenes"]

This is what i have done till now.

let arr1 = ["abracadabra", "allottee", "assessee"];
let arr2 = ["kelless", "keenness"];

function dup(input) {
  return input.map(e => {
    let tempOp = ''
    for (let i = 0; i < e.length; i++) {
      if (i === 0) tempOp += e[i];
      else if (e[i - 1] !== e[i]) tempOp += e[i]
    }
    return tempOp;
  })
}
console.log(dup(arr1))
console.log(dup(arr2))

I can do it with for loop. But is there any other better way of doing it. Can i do it with regex if yes any direction will help a lot.


1 Answers

You can try the following Regex:

(.)\1+

and then replace the matches with $1. That means:

Replace multiple occurrences with the match of first capturing group, which is . (matches any character only once).

let arr = [
  'abracadabra',
  'allottee',
  'assessee',
  'Gooooooooooooooogle',
  'Vacuum'
];

arr = arr.map(val => val.replace(/(.)\1+/g, '$1'));
console.log(arr);
like image 186
vrintle Avatar answered Oct 21 '25 18:10

vrintle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!