Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!