Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 …
function myReplace(str, before, after) {
//search for the before string and then use a function to check for capitalisation before replacing.
str = str.replace(before, function(x){
//check whether the first letter of before is a capital
//replace after with a capitalised first letter and then
//the rest of the string, cannot just replace first letter as its read only.
if(before[0] == before[0].toUpperCase()){
after = after[0].toUpperCase() + after.slice(1);
return after;
}
return after;
});
return str;
}
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