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

279
Visualizações
Making a function using .replace() to remove multiple characters in a variable string?

The function accepts 3 inputs: (string (str), starting point in string (index), and how many characters to remove after that (count)).

function removeFromString(str, index, count) {
  let newStr = '';
  for (let i = index; i <= (index + count); i++) {
    newStr = str.replace(str[i], '');
  }
  return newStr;
}

It's returning outputs that may remove one character at most, but nothing more than that, which is not what I am trying to achieve.

What I want is a function that when called, will return a function without the characters specified from the index and count parameters.

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

0

With

newStr = str.replace(str[i], '')

you're always taking str as the base string to replace - which is the original input. You're never using the newStr except after the final iteration; all replacements made before then are lost.

Another problem is that str.replace(str[i], '') will replace the same character if it exists earlier in the string, rather than at the index you want.

Slice the string's indicies instead.

const removeFromString = (str, index, count) => (
  str.slice(0, index + 1) + str.slice(index + count + 1)
);
console.log(removeFromString('123456', 2, 2));

about 4 years ago · Juan Pablo Isaza Relatório

0

Is just a matter of use substring method from JS.

Substring method definition from Mozilla Developer Network

    function removeFromString(str, index, count) {
       return str.substring(0, index) + str.substring(index+count);
    }
    console.log(removeFromString('fofonka', 2, 2));

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