Home > OS >  Write a javascript program to Delete Even occurrences in a given string
Write a javascript program to Delete Even occurrences in a given string

Time:12-08

I am finding problem in JavaScript code. Write a JavaScript program to delete even occurrence in given string using function. for example :

Input AAABBBCCC
OUTPUT: AABBCC (delet bold letters)

Input: AAAABBBBCCCC
OUTPUT: AABBCC

i am facing problem in function

CodePudding user response:

A single regex should work:

console.log(remove('AAABBBCCC'))
console.log(remove('AAAABBBBCCCC')) 

function remove(str) {
  return str.replace(/(.)\1/g, '$1')
}

(.)\1 matches duplicated characters

CodePudding user response:

Solution with a for loop:

function stripEven(str) {
  let res = '';
  let counter = 0;
  for (let i = 0; i < str.length; i  ) {
    if (str[i] !== str[i-1]) counter = 0;
    if (counter % 2 === 0) res  = str[i];
    counter  ;
  }
  return res;
}

console.log(stripEven('AAABBBCCC'))
console.log(stripEven('AAAABBBBCCCC'))
console.log(stripEven('AAABBCCC'))

  • Related