Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 16, 2018 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/5bce47fa44a04419badfb5084b27f098 to your computer and use it in GitHub Desktop.
Save nickihastings/5bce47fa44a04419badfb5084b27f098 to your computer and use it in GitHub Desktop.
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");
@Mybigjay
Copy link

Mybigjay commented Aug 5, 2022

function myReplace(str, before, after) {
let ifUpperCase = before.match(/^[A-Z]/);
if (ifUpperCase == null) {
return str
.replace(before, after.toLowerCase());
} return str
.replace(before, after[0].toUpperCase() + after.slice(1));
}

console.log(myReplace("I think we should look up there", "Up", "Down"));

@ekada
Copy link

ekada commented Jul 5, 2023

`function myReplace(str, before, after) {
return /[A-Z]/.
test(before)?str.replace(before,(after[0]
.toUpperCase())
.concat(after
.slice(1))):
str
.replace(before,(after[0].
toLowerCase())
.concat(after.slice(1)));
return str.replace(before,after);

}

console.log(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