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

103
Vistas
JavaScript replace characters with for loop

This is a simple program to replace the characters of a string with another using for loop and if statements. However, I was not getting the desired result I want to get. Here is the code:

var str1 = "Optimism is the key to victory"

var str2 = ""

for(let i=0; i<str1.length;i++){
  if(str1[i] == "i"){
    var temp = str1[i]
    temp = "1"
    str2 += temp
  }
  if(str1[i] == "e"){
    var temp2 = str1[i]
    temp2 = "3"
    str2 += temp2
  }
  else{
    str2 += str1[i]
    }
 }
console.log(str2)

The result is this: "Opt1im1ism 1is th3 k3y to v1ictory" Why does it add another 'i' after '1' and how do I remove it? (thanks for the response in advance!)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You have

if (...) {
  ...
}
if (...) {
  ...
}
else {
  ...
}

The first if is not chained with the later two blocks - whenever the first condition is fulfilled, one of the other conditions will necessarily be fulfilled as well, resulting in str2 being concatenated to twice in a single iteration instead of once.

Use else/if instead.

var str1 = "Optimism is the key to victory"

var str2 = ""

for (let i = 0; i < str1.length; i++) {
  if (str1[i] == "i") {
    var temp = str1[i]
    temp = "1"
    str2 += temp
  } else if (str1[i] == "e") {
    var temp2 = str1[i]
    temp2 = "3"
    str2 += temp2
  } else {
    str2 += str1[i]
  }
}
console.log(str2)

More elegantly:

var str1 = "Optimism is the key to victory"

var str2 = ""

for (let i = 0; i < str1.length; i++) {
  if (str1[i] == "i") {
    str2 += "1"
  } else if (str1[i] == "e") {
    str2 += "3"
  } else {
    str2 += str1[i]
  }
}
console.log(str2)

Or ditch the indicies, they aren't helping much:

var str1 = "Optimism is the key to victory"

var str2 = ""

for (const char of str1) {
  if (char == "i") {
    str2 += "1"
  } else if (char == "e") {
    str2 += "3"
  } else {
    str2 += char
  }
}
console.log(str2)

Or even

const str1 = "Optimism is the key to victory"
const str2 = str1.replace(/[ie]/g, char => char === 'i' ? '1' : '3');
console.log(str2)

about 4 years ago · Juan Pablo Isaza Denunciar

0

What your code does is create two separate if else blocks.

First if checks for i . Second if-else checks for e or not e. Now the character i satisfies the first if condition and second else condition. That is why the code in both blocks get executed when the character i is encountered.

Use else if

var str1 = "Optimism is the key to victory"

var str2 = ""

for(let i=0; i<str1.length;i++){
  if(str1[i] == "i"){
    var temp = str1[i]
    temp = "1"
    str2 += temp
  }
  else if(str1[i] == "e"){
    var temp2 = str1[i]
    temp2 = "3"
    str2 += temp2
  }
  else{
    str2 += str1[i]
    }
 }
console.log(str2)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can easily achieve the result first split the string, and then map over the string array to replace it with a replacement string using dict and finally join the string to get the final result.

var str1 = "Optimism is the key to victory";
const dict = {
  i: 1,
  e: 3,
};
const result = str1
  .split("")
  .map((c) => (dict[c] ? dict[c] : c))
  .join("");

console.log(result);

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