Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
How to remove only one of repeated chars in string using JavaScript

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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');
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda