Reputation: 23226
I am trying to remove consecutive duplicate characters from the string. So the input of aabbcde
should output as cde
.
I wrote the following code, but I am getting the incorrect output. I could not understand why.
var a = "aabbccddeef"
var ncopy = a;
let leftPointer = 0;
let rightPointer = 1;
let posList = [];
while (true) {
if (a[leftPointer] == a[rightPointer]) {
ncopy = ncopy.replace(a.slice(leftPointer, rightPointer + 1), '')
leftPointer += 2
rightPointer = leftPointer + 1;
if (leftPointer >= a.length || rightPointer >= a.length) {
break;
}
} else {
leftPointer++;
rightPointer++;
}
}
console.log(ncopy);
Upvotes: 1
Views: 1128
Reputation: 28111
You can do this with a simple regex:
'aabbbcde'.replace(/(.)\1+/g, '')
Result:
'cde'
Snippet:
var a = 'aabbbcde';
var result = a.replace(/(.)\1+/g, '');
console.log(result);
Upvotes: 2
Reputation: 1712
You can do it with a following recursive function:
const input = 'aabbccddeeffg';
function getResult(str) {
const newStr = str.match(/(.)\1*/g).filter(str => !((str.length % 2 === 0) && (str.split('').every((char,i,arr) => char === arr[0])))).join('');
return newStr === str ? newStr : getResult(newStr)
}
const result = getResult(input);
console.log(result);
Upvotes: 0
Reputation: 9427
'aabbccde'
.split('')
.reduce(
(acc, cur) => {
if (acc.indexOf(cur) !== -1) {
return acc.slice(acc.length);
}
return [...acc, cur];
}
)
.join('')
Upvotes: 1