I want to find a word in the string and replace it with new one. If the first letter in the word is upper case, the function should replace it with upper case, for example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".
Is there a better solution than this:
function myReplace(str, before, after) {
var arr = str.split(" ");
if(arr.indexOf(before) > -1){
if(/[a-z]/.test(before[0])){
arr.splice(arr.indexOf(before), 1, after);
}else if(/[A-Z]/.test(before[0])){
arr.splice(arr.indexOf(before), 1, after[0].toUpperCase() + after.slice(1));
}
}
return arr.join(" ");
}
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
//Should return "He is Sitting on the couch"
myReplace("Let us go to the store", "store", "mall");
//Should return "Let us go to the mall"
myReplace("His name is Tom", "Tom", "john");
//Should return "His name is John"
1 Answer 1
It doesn't look great to split words, mutate the array, then join back. It might be better (and simpler) using a regex.
The logic of matching the case of the starting letter of the replacement has some problems:
- Instead of applying the case transformation for each match, you could apply it once to the
after
parameter - The replacement is not symmetric: if
before
starts with uppercase, you transformafter
to start with uppercase, but you don't do it the other way around, despite saying "vice versa" in your description. - It would be good to clarify what should happen if
before
orafter
are mixed case, for examplesLEEping
->SiTTIng
With the above suggestions applied, a simpler, cleaner and more efficient implementation:
function myReplace(str, before, after) {
if (/[A-Z]/.test(before)) {
after = after[0].toUpperCase() + after.slice(1);
}
return str.replace(new RegExp(before, 'g'), after);
}
>
at the beginning of this post as your text is not a quote. \$\endgroup\$