Search and Replace FCC Algorithm Challenge

jackLyons Free Code Camp

I don’t know about you, but after the last bonfire challenge this one was almost too easy. In this post I will show you how to write a simple search & replace algorithm. You could almost write this in literal pseudo code and get it to work!

Things to know:

How to solve the challenge:

Step 1: Write out your pseudo logic.

From the outset, all I could see was that you are required to simply replace one word with another with the only exception to retain the words case where required. At first, I thought there would be more of a challenge in terms of finding words with upper and lower camelCase like properties. But when looking at the test cases, it really only required the first letter to be replaced.

So if we were to write some pseudo code, it might look something like this:

 * if the first letter of the before OR after word is upper case, 
 * then make sure the corresponding before OR after word is returned with 
 * an uppercase character. 

Step 2: Code it up!

So basically, you can knock this out in a one lined if statement…

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

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


Things to note:

  • if the word/variable BEFORE is uppercase, then make sure the word/variable AFTER is uppercase too.
  • Concatenate the after string by using the slice method starting from the 2nd letter.
  • If you are unfamiliar with slice, then you can read up on it here.

And that’s it. You’re done with this challenge!

For any questions, comments or feedback please don’t hesitate to leave me a comment below.

Sign up to receive up-to-date web tips, tricks and code hacks!