So, I’ve been playing with Title Case a Sentence in Basic Algorithms and trying to resolve the challenge with out dumping the string into an array, or words, because… Maybe I can’t.
My premise is I would work out a function where it would look for a space, return the position, I’d increment that number by one, to find the next position, which should be the first letter of the first word.
A) I created a FOR loop where the counter started at zero and would run until it exceed the strings length .
for (var i = 0; i < str.length; i++) {
At each run of the loop it would test the position in the string to see if it was a space. If it tested true, then it would replace replace the character after the space with the same character in upper case.
I thought that if the IF statement was testing TRUE to a " ", then the first letter in the word would be: i + 1.
if (str[i] === " "){
str = str.replace(str[i+1], str[i+1].toUpperCase); }
I had two problems. The first was: str[i+1].toUpperCase. It hated that.
I decided I’d troubleshoot toUpperCase after, So in order to see if it was at least finding the correct position, I just tried to have the replace function take the index position after a space and turn it into an ‘X’.
str = str.replace(str[i+1], “X”);
This returned:
I’m X XiXtle tea Xot.
okay…? That was random, not what I expected. Thought I’d loose the +1 for a moment and just see if it was finding a space and turning it into an X
str = str.replace(str[i], “X”);
yields:
I’mXaXlittleXteaXpot.
Okay!! That works, but why does it fall apart with str[i+1]???
I realize I could spit this into an array and do that way, but this felt more fun/lazy/challenging. I’m at a meetup now and the guy next to me solved the problem with out using arrays, but did an approach without a loop.
I also realize, this wouldn’t handle the first character of the first word in a sentence, but that could be resolved with one line at the beginning of the function.
My first time using the forum, so I hope I explained myself correctly.
function titleCase(str) {
var i;
for (i=0; i<str.length; i++){
if (str[i] === " "){
str = str.replace(str[i+1], str[i+1].toUpperCase);
}
}
return str;
}
titleCase(“I’m a little tea pot”);