I am writing a program which takes three parameters e.g, sentence, wordtoreplace, toReplaceWith.
program should return sentence string with wordtoreplace should be replaced with toReplaceWith. And if the wordtoreplace is a capitalized word then the replaced world should also be capitalized. I tried many times but my code doesn't work. Help please.
function myReplace(str, before, after) {
var words = str.split(" ");
var indexOfWord = words.indexOf(before);
if ( before.charAt(0) === before.charAt(0).toUpperCase ) {
after = capitalize(after);
}
str = str.replace(new RegExp(before), after);
function capitalize( word ) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return str.replace(new RegExp(after, 'i', 'g'), after);;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
RegExpdoes not take three arguments. You need to calltoUpperCase()with parentheses. You don't use words or indexOfWord once they are initialised. Why do you have them? But it seems a bit redundant to apply the capitalisation when the caller of your function could easily provide the capital letter? It makes the function non-user-friendly.