Created
March 16, 2018 20:11
-
-
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 …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
`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
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"));