Free Code Camp Bonfire Challenge: Search and Replace

Posted by

The objective of this challenge (as stated on FCC’s website) is to …

  • Perform a search and replace on the sentence using the arguments provided and return the new sentence.
  • First argument is the sentence to perform the search and replace on.
  • Second argument is the word that you will be replacing (before).
  • Third argument is what you will be replacing the second argument with (after).
  • NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to replace the word “Book” with the word “dog”, it should be replaced as “Dog”

Three JavaScript methods were included to help solve the challenge.

 

Here is what was giving as a starting point to solve the problem:


function myReplace(str, before, after) {
  return str;
}

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

My solution:


function myReplace(str, before, after) {
	var firstBeforeChar = before.charAt(0);
	if(firstBeforeChar===firstBeforeChar.toUpperCase()){
		after = after.charAt(0).toUpperCase() + after.slice(1);

	}
str = str.replace(before, after);

  return str;
}

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

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s