Skip to content

Instantly share code, notes, and snippets.

@eday69
Last active June 15, 2018 17:57
Show Gist options
  • Save eday69/be8e15c20648dce4e4dbf5d78ffe70a1 to your computer and use it in GitHub Desktop.
Save eday69/be8e15c20648dce4e4dbf5d78ffe70a1 to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Search and Replace
// 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 first character in 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"
function myReplace(str, before, after) {
if (before.toLowerCase() !== before) {
after=after.charAt(0).toUpperCase() + after.substring(1);
}
return str.replace(before, after);
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment