Home > database >  How to remove only one of repeated chars in string using JavaScript
How to remove only one of repeated chars in string using JavaScript

Time:02-14

I have a string with repeated chars like : 'CANADA'.
And I am trying to get the string which removed only one of repeated chars :
'CNADA', 'CANDA', 'CANAD'.

I've tried it with subString, but it returned the part of string removed. Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').

What is the way of removing only one char at time? The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])

Thank you.

CodePudding user response:

You can achieve this by utilizing the second parameter of String#indexOf() which specifies the position from which to start the search. Here in a while loop, and using a Set to remove dulplicates before returning.

function getReplaceOptions(str, char) {
  let res = [], i = str.indexOf(char, 0);
  while (i !== -1) {
    res.push(str.substring(0, i)   str.substring(  i));
    i = str.indexOf(char, i)
  }
  return Array.from(new Set(res))
}

console.log(getReplaceOptions('CANADA', 'A'));
console.log(getReplaceOptions('Mississippi', 's'));

CodePudding user response:

You can first count all the occurrences in the string. Later you can iterate over the script and if the count is greater than 1 you can remove that character.

const theString = 'CANADA'
const letterCount = {}
const resultArr = []

for (var i = 0; i < theString.length; i  ) {
  const theLetter = theString.charAt(i)
  if(letterCount[theLetter]){
    letterCount[theLetter] = letterCount[theLetter]   1
  }
  else{
    letterCount[theLetter] = 1
  }
}
console.log(letterCount)
for (var i = 0; i < theString.length; i  ) {
  const theLetter = theString.charAt(i)
  if(letterCount[theLetter] && letterCount[theLetter] > 1){
   resultArr.push(theString.substr(0, i)   theString.substr(i   1))
  }
}

console.log(resultArr)

CodePudding user response:

If you want to remove only the first repeating character then you can use matchAll here as:

Just see the browser compatibility before using this

const str = 'CANADA';
const firstRepeatedChar = 'A';
const result = [];

for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index)   str.slice(index   1));
}

console.log(result);


NOTE: If you want to search for the first repeating character then remove it, then you can do as:

const str = 'CANADA';

let firstRepeatedChar = '';
const set = new Set();
for (let i = 0; i < str.length;   i) {
  if (!set.has(str[i])) {
    set.add(str[i]);
  } else {
    firstRepeatedChar = str[i];
    break;
  }
}

const result = [];
for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index)   str.slice(index   1));
}

console.log(result);

CodePudding user response:

You could use some Array magic to remove duplicate characters:

function removeDuplicateCharacters(value) {

    // convert string to array and loop through each character
    return String(value).split('').filter(function(char, index, all) {

        // return false if char found at a different index
        return (index === all.indexOf(char));
    })
    .join(''); // convert back to a string
}
// returns `CAND`
removeDuplicateCharacters('CANADA');

// returns `helo wrd`
removeDuplicateCharacters('hello world');
  • Related