I've been solving katas on codewars and I stumbled upon a general code problem that I can't seem to find an answer to.
This is my code:
function wave(str) {
let arr = [];
for (var i = 0; i < str.length; i++) {
str[i].match(/\S/) && arr.push(str.replace(str[i], str[i].toUpperCase()));
}
return arr;
};
(Note: Input is always lowercase.)
In the case of wave("abc def"); the code does exactly what I want it to:
["Abc def", "aBc def", "abC def", "abc Def", "abc dEf", "abc deF"]
=> Function takes a string, capitalizes one letter of the string starting at str[0], pushes the new word to arr, increments i and repeats process until i < str.length, then returns arr with all the results.
However, if I input wave("acc def"); for example, only the first occurrence of the letter c will return capitalized:
["Acc def", "aCc def", "aCc def", "acc Def", "acc dEf", "acc deF"]
Question: Why does it 'jump' the second occurrence of 'c' and how can I target the second or nth occurrence of a character in a string?
/\S/g?str.replace(str[i], ...)will only replace the first occurrence of the character atstr[i](hence it would also not work withcac def)str[i](.slice()), take the uppercase version ofstr[i], take the part right ofstr[i](.slice()) - combine them again