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

140
Vistas
Why am I getting the wrong output while using str.replace()?

My code has an index value that points to a character in a string and I have to replace all the instances of that character with the previous value and the next value alternatively except the value of the given index character. Below is my code to implement this:

function replaceChar(string,idx){
    
    a = string[idx]
    b= []
    pre_val = string[idx - 1] 
    post_val = string[idx + 1]
    for(let i=0; i< string.length ; i++){
        if(i==idx){
            continue
        }
        if (string[i]===a){
            b.push(i)
        }
    }
    for(i=0; i<b.length; i++){
        if (i%2==0){
            string = string.replace( string[b[i]],pre_val)
        }
        if (i%2==1){
            string = string.replace(string[b[i]],post_val)
        }
    }
    return string
}

The input given is:

console.log(replaceChar('Baddy',2))

The preferred output is:

Baday

What I get is:

Baady


string = string.replace( string[b[i]],pre_val) 

=> The value of b[i] in the above statement is 3 and so string[3] should be replaced with a (the previous value) and the output should be Baday. Not sure what is wrong.

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

0

Since you want to replace a character at a certain index and you are doing multiple replacements (potentially) you can use an array instead (temporarily):

let tmp = string.split(''); //from string into array
for(let i = 0; i<b.length; i++){
    if (i%2==0){
        tmp[b[i]] = pre_val;
    }
    if (i%2==1){
        tmp[b[i]] = post_val;
    }
}
return tmp.join('') //back into a string

Also, you need to declare your other variables correctly.

    let a = string[idx]
    let b = []
    let pre_val = string[idx - 1] 
    let post_val = string[idx + 1]
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