Skip to content

Instantly share code, notes, and snippets.

@sedera-tax
Created February 28, 2016 11:23
Show Gist options
  • Save sedera-tax/4c70fa915147fe5ecf14 to your computer and use it in GitHub Desktop.
Save sedera-tax/4c70fa915147fe5ecf14 to your computer and use it in GitHub Desktop.
function myReplace(str, before, after) {
var test = before.slice(0,1);
var testMaj = test.toUpperCase();
if(test === testMaj){
after = after.charAt(0).toUpperCase() + after.substring(1).toLowerCase();
}
str = str.replace(before, after);
return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
@sedera-tax
Copy link
Author

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment