Reputation: 667
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");
Upvotes: 0
Views: 98
Reputation: 16
You missed the parenthesis at the .toUpperCase()
function in your if
statement.
I have also tried to make your version a bit cleaner, maybe it will help you.
function replace(sentence, wordToReplaced, newWord) {
if (sentence.includes(wordToReplaced)) {
var char = wordToReplaced.charAt(0);
if (char === char.toUpperCase()) {
newWord = newWord.charAt(0).toUpperCase() + newWord.slice(1);
}
sentence = sentence.replace(wordToReplaced, newWord);
}
return sentence;
}
Upvotes: 0
Reputation: 2970
Try this:
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('\\b' + before + '\\b'), after);
function capitalize( word ) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return str.replace(new RegExp(after, 'i', 'g'), after);;
}
You can use '\\b' for find in the string. You can test the code here: http://www.w3schools.com/code/tryit.asp?filename=FBQS72BU7H97
Here the doc: http://www.w3schools.com/jsref/jsref_regexp_begin.asp
Upvotes: 1
Reputation: 463
You should probably invoke toUpperCase
within your if
statement
if ( before.charAt(0) === before.charAt(0).toUpperCase() ) {
after = capitalize(after);
}
Upvotes: 1