I am solving this code wars kata problem that requires me to return a string in a weird case such that the first letter is in uppercase and the next is in lowercase and so on.
Here is the link to the question
I came up with this code:
function toWeirdCase(string){
var r = string
let newString = [];
for( let i in string ) {
if(i%2 == 0){
newString.push(string[i].toUpperCase());
} else {
newString.push(string[i].toLowerCase());
}
}
return newString.join('');
}
I am stuck because I cannot be able to account for the space and I need the next word to start with a capital letter.
2
Answers
Instead of doing it char by char, which will introduce a few unnecessary ifs. (since you can’t just look for odd/even letters, you have to take into account spaces and new words). You can start by splitting the string into words. and then work on each word separately. That way there are less rules, you start with the Uppercase every time, and after you finish that, just join them again. Something like this:
Here’s a solution based on your approach where you
.split()
the inputstring
first into separate words before performing the actual capitalization of each char.