Intermediate Algorithm Scripting: Search and Replace(with arrays))

Tell us what’s happening:
Hi, i am triying to do this challenge with arrays, but i can’t manage to preserve the case in the first replaced word.

Your code so far


function myReplace(str, before, after) {
let sentence = str.split(" ");
for(var i = 0; i < sentence.length; i++){
  if(sentence[i] == before){
    sentence[i] = after;
  }else{
    if(sentence[i] == before && sentence[i].charAt(0) == before.charAt(0).toUpperCase()){
    sentence[i] = after.charAt(0).toUpperCase() + after.slice(1);
  }
  }
  
}
return sentence.join(" ");
}

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

console.log(result);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Search and Replace

Link to the challenge:

Take a closer look at if clauses in the function and try to check whether they behave as expected. You can also follow one of the troublesome examples by hand.

i know it’s kinda messy but it’s working, but now it doesn’t pass the " myReplace("I think we should look up there", "up", "Down") should return “I think we should look down there”." part

function myReplace(str, before, after) {
  let sentence = str.split(" ");
  for(var i = 0; i < sentence.length; i++){
    if(sentence[i] == before && sentence[i].charAt(0) == before.charAt(0).toUpperCase()){
      sentence[i] = sentence[i] = after.charAt(0).toUpperCase() + after.slice(1);
    }else{
      if(sentence[i] == before){
        sentence[i] = after;
      }
    }
    }

  console.log(sentence);
  return sentence.join(" ");

    
  }

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

Notice that right now character case of after is explicitly matched/changed only if word in original string is uppercase. In other cases the after is used as is.

1 Like