Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 16:00
Show Gist options
  • Save rfprod/98049c85704fe334f03c to your computer and use it in GitHub Desktop.
Save rfprod/98049c85704fe334f03c to your computer and use it in GitHub Desktop.
Search And Replace
function searchAndReplace(str, before, after) {
var strArr = str.split(" ");
var firstLetter = before[0];
var firstAfterUpper = after[0].toUpperCase();
if (firstLetter == firstLetter.toUpperCase()){
after[0] = firstAfterUpper;
after = after.replace(after[0],firstAfterUpper);
}else{
}
for (var i=0;i<strArr.length;i++){
if (strArr[i] === before){
strArr[i] = after;
}
}
var output = strArr.join(" ");
return output;
}
searchAndReplace("He is Sleeping on the couch", "Sleeping", "sitting") ;

Search And Replace

Performs a search and replace on the sentence using the arguments provided and returns 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: Preserves 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 will be replaced as "Dog".

A script by V.

License.

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