Why is my solution not working for the problem Search and Replace?

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**
function myReplace(str, before, after) {
let myArr = before === after ? 0 : after.charAt(0).toUpperCase() + after.slice(1)

return  str
.replace(before,myArr)
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Search and Replace

Link to the challenge:

Why are you checking if before === after in your ternary? Also, why are you always capitalizing the the after?

Also, why would you name something that is supposed to be a string myArr?

the myArr was just something I came up with on the spot. I should change that to myStr. I’m trying to figure out a way that instead of having before ===after I can check if the first letter is lowercase in before and after. There for just returning after before === after ? after : after.charAt(0).toUpperCase() + after.slice(1). I guess my only issue is to find a way to do that.

You only need to be concerned about the case of before according to the instructions. So how would you get the first character of before and determine its case?

Let me give you an algorithm to attempt to code.

If the first letter of before is the same as the uppercase version of the first letter of after, then change after to be the uppercase version of the first letter of after concatenated with the remaining letters of after. Otherwise, change after to be the lowercase version of the first letter of after concatenated with the remaining letters of after. Finally, return a new string by replacing before with the current after in str.

1 Like

I ended up figuring out using my method. What do you think of it?
function myReplace(str, before, after) {
let myAfter = before[0].toUpperCase() === before[0] ? after.charAt(0).toUpperCase() + after.slice(1) : after
let myBefore = before[0].toLowerCase() === before[0] ? after.charAt(0).toLowerCase() + after.slice(1): before
return str
.replace(before,myAfter)
.replace(after, myBefore)
}

console.log(myReplace(“He is sleeping on the couch”, “sleeping”, “Sitting”));