The first issue I see is the for loop structure, I think what you are trying to achieve is a “while” loop using a “for” loop. I’m not saying use a while loop but just look at the syntax and structure first and move forward from there.
for (var i=0;i<str.length;i++) {}
this should be your for-loop to help you get on track
Try to step through your algorithm with a string that is failing. You could use a debugger, but it’s easier to just console.log what you got as input and what you replaced it with (at i, str, newstr). In each loop iteration.