Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda