"Search and Replace" challenge [Solved]

Hope you could help me please,

There is the “Search and Replace” challenge
and I wrote this code:

function myReplace(str, before, after) {
  var ans="";
  var index=str.indexOf(before);
  var prevStr=str.substr(0,index);
  var nextStr=str.substr(index+1+before.length,str.length);  
  if(before.charAt(0).charCodeAt()>=65 && before.charAt(0).charCodeAt()<=90){
    var c= after.charAt(0).toUpperCase();
  ans=prevStr+after+" "+nextStr;
  return ans;

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

From some reason, if I disable the comment on the line "ans=ans.substr(0,ans.length-1);"
some test are working and other do not, and if I comment that line so the test that worked, not working, and those who not work, are working.

Hope I was cleare enough…
You can just copy and paste and see for yourselves…

Thank you

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

OK your code as posted with the line commented out is returning correct results for tests:

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
myReplace("This has a spellngi error", "spellngi", "spelling");

The reason it is not returning correct results for the other three tests is that there is a final whitespace at the end of each sentence. When you uncomment your line of code this removes one character from the string, making the original two results fail and therefore the other three correct.

Hope this points you in the right direction.

replace() solved that problem

Thank you