Intermediate Algorithm Scripting - Search and Replace

wrote this code for my algo but didn’t work I tested it using console.log() and it worked
Describe your issue in detail here.

Your code so far

function myReplace(str, before, after) {
      let arr = str.split(/\s/)
let position = arr.indexOf(before)
    let newArr = [...arr]
    newArr[position] = after
    let test= newArr.join(" ")
    return test
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Search and Replace

Link to the challenge:

Which test cases are failing? I suspect you have case issues.

1 Like

as Jeremy mentioned, you have case issues.
So for eg:
when given this input:

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

should return the string

He is Sitting on the couch

But you are returning:
He is sitting on the couch

And the difference is that you didn’t keep the case of the word being replaced.

ooh sorry didn’t notice that, thanks for the correction

1 Like

*this is the correct answer *

function myReplace(str, before, after) {
    let arr = str.split(/\s/)

    console.log(arr.indexOf(before))
let position = arr.indexOf(before)
if (/^[A-Z]/.test(before)) {
    after = after[0].toUpperCase() + after.substring(1)
  } else {
    after = after[0].toLowerCase() + after.substring(1)
  }
    let newArr = [...arr]
    newArr[position] = after
    return newArr.join(" ")
  }

had to look up the correction painful but found a fix

We have blurred this solution so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

okay bro thanks for pointing out the error for me