Easy Beginner Solution - Search and Replace

Continuing the discussion from freeCodeCamp Challenge Guide: Search and Replace:

Hello everyone,

After contributing to previous problem of Pig Latin with the community… it is feeling great to do for another one, hope this is an easy one for many of the beginners, I am also open for code review discussions:

function myReplace(str, before, after) {
// Storing “after” parameter in a new variable to perform few tasks
var newAfter = after;
let afterLength = after.length;

// Task of checking whether the first character of “before” is in Uppercase
if(before.charAt(0) === before.charAt(0).toUpperCase()){
newAfter = after.charAt(0).toUpperCase();
after = after.slice(1, afterLength);
return str.replace(before, newAfter + after);
}

// Task of checking whether the first character of “before” is in lowercase
else if(before.charAt(0) === before.charAt(0).toLowerCase()){
newAfter = after.charAt(0).toLowerCase();
after = after.slice(1, afterLength);
return str.replace(before, newAfter + after);
}
}

myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”);
myReplace(“I think we should look up there”, “up”, “Down”);
myReplace(“His name is Tom”, “Tom”, “john”);

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

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