Home > Back-end >  Why am I getting the wrong output while using str.replace()?
Why am I getting the wrong output while using str.replace()?

Time:09-21

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.

CodePudding user response:

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]
  • Related