I sometimes get confused when the solution I am thinking of is not using all of the functions provided in the description under "useful links".
But they seem to be suggestions. Sometimes I use one or two of them and sometimes none, which is fine, as long as I get to a solution which works and which I understand.
In the case of this bonfire, I went step by step, made sure the string was replaced and then took care of the necessity to preserve the case of the original (before) word.
Some more tweaks had to be made, such as to join the "after" term again at an appropriate occasion.
function replace(str, before, after) {
str = str.split(" ");
for (var i = 0; i < str.length; i++) {
if (str[i] === before) {
before = before.split("");
after = after.split("");
if (before[0] === before[0].toUpperCase()) {
after[0] = after[0].toUpperCase();
}
after = after.join("");
str[i] = after;
}
}
str = str.join(" ");
return str;
}
The code is tested with differentsample data, but the purpose is to find the part in str which equals before and replace it with the content of after.
If before is uppercase, the substituted string must be uppercase after insertion as well.
That's it for today, I guess ;)
Keine Kommentare:
Kommentar veröffentlichen