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

138
Visualizações
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 Respostas
Responde à pergunta

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 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