Https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace

Hey guys why are we checking if before[0] === before[0].toUpperCase()? I understand it’s checking if the first letter is capitalized but if you look at the case test, both jumped and leaped are already lowercase… below is my current solution.

function myReplace(str, before, after) {
if(before[0] === before[0].toUpperCase()){
after= after[0].toUpperCase() + after.slice(1);
}
return str.replace(before, after);
}

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

The point of the function is to replace the word, in its matching case. So yes, in this test, jumped is lowercase, but what if the function was called like this:

myReplace("Dear Employer,", "Employer", "gertrude");

The function should be able to be used for many cases.

Right in this case Employer is capitalize, hence we should replace it with gertrude and take the first letter and capitalize it which would be Gertrude. Is that the right approach?

1 Like

yes. keep case from before and apply to after.
then replace.
(see all tests performed bottom left)

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.