Search and Replace (FreeCodeCamp intermediate algorithm scripting)
This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...

Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.

Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.



function myReplace(str, before, after) {
  return str.replace(new RegExp(before, 'g'), match =&gt; {
    return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
  })
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))