I have a function where I am iterating through a given string, alternating the capitalisation of each character and concatenating it to variable alt.
In order to loop through this properly, I have removed spaces from the original string. But I need to add them back at the end of the function.
function alternatingCaps(str) { // 'hello world'
let words = str.toLowerCase().split(' '); // ['hello','world']
str = words.join(''); // 'helloworld'
let alt = '';
for(let i = 0; i < str.length; i++) {
if(i % 2 === 0)
alt += str[i].toUpperCase();
else
alt += str[i].toLowerCase();
}
return alt;
}
console.log(alternatingCaps('hello world'));
/* Output: "HeLlOwOrLd"
Wanted output: "HeLlO wOrLd" */
Once alt contains a string included as a value in the words array, I want to add a space at the end of the word.
Here was my attempt:
words.forEach(function(word) {
if(alt.toLowerCase().includes(word) && word[word.length - 1] === alt[i].toLowerCase())
alt += ' ';
});
It checks if any of the words in the words array are present in the alt string and if the current character iteration of the string corresponds to the last letter in the word. If so, it adds a space to the string.
But this does not work as intended.
> Output: "HeLlO wOr Ld"
> Wanted output: "HeLlO wOrLd"
I also imagine this would cause problems with duplicate letters. How can I accomplish my goal?