Please Help Basic Algorithm Scripting: Title Case a Sentence

Hi, this is what I’ve written so far. From what I can tell, my for loop is doing nothing at all. I’m not sure if my syntax is wrong, or if my logic is off. Any help is appreciated. Thanks.


function titleCase(str) {
str = str.toLowerCase();
var arr = str.split(" ");
for (var i=0; i<arr.length; i++) {
  var temp = arr[i];
  temp.toUpperCase(temp.charAt(0));
  arr[i].replace(arr[i],temp);
}
var newStr = arr.join(" ");
return newStr;
}


titleCase("I'm a little tea pot");
console.log(titleCase("sHoRt AnD sToUt"));


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:

Hey there,

to uppercase a string you just call the method without any arguments (ie) "hello".toUpperCase()

You can see the docs for toUpperCase() here: https://www.w3schools.com/jsref/jsref_touppercase.asp

Here’s a solution I came up with:

function titleCase(str) {
  str = str.toLowerCase();
  const wordsInString = str.split(' ')

  const titleCasedWords = wordsInString.map(word => {
    const firstLetterOfWord = word[0]
    const restOfWordAfterFirstLetter = word.slice(1)
    return firstLetterOfWord.toUpperCase() + restOfWordAfterFirstLetter
  })

  return titleCasedWords.join(' ')

}


titleCase("I'm a little tea pot");
console.log(titleCase("sHoRt AnD sToUt"))

It’s not that your for loop is doing nothing. The problem occurs specifically at this line.
arr[i].replace(arr[i],temp);

Since strings are immutable values, methods on strings return entirely new strings. So when you call replace, you’re not changing the string values in the array. You could always assign the strings returned by replace to the current array index though.

1 Like

Hi Jack and Drant, thanks so much for the feedback. I managed to get it done. It’s rather inelegant, but it works.

function titleCase(str) {
str = str.toLowerCase();
var arr = str.split(" “);
var arr2 = [ ];
for (var i=0; i<arr.length; i++) {
var temp = arr[i];
var firstLetter = temp.slice(0,1);
var temp = firstLetter.toUpperCase() + temp.substring(1);
arr2.push(temp);
}
var newStr = arr2.join(” ");
return newStr;
}