-1

i have a task for my homework where i have to write a function that will capitalize each word in a sentence that is written into that function. The idea i had was to convert each word into an array, make a loop targeting first letter of each item of that array, and then turning that array back into a string. The code i came up with is this

function titleCase(string) {
  var words = string.split(' ');
  for (var i = 0; i < words.length; i++) {
    const lettersUp = ((words[i])[0]).toUpperCase();
    const result = words[i].replace((words[i])[0], lettersUp);
    return result;
  }
}

The problem i have now is that it returns only the first word of an array. From troubleshooting i have been doing i have a feeling i messed up the loop but i just have no idea how. Any help would be greatly appreciated. Thanks.

Foxford
  • 1
  • 1

2 Answers2

0

You are returning from the first iteration, so your code won't work.

What you are looking for is something like this:

function titleCase(string) {
    var words = string.split(" ");
    for (var i = 0; i < words.length; i++) {
        const lettersUp = ((words[i])[0]).toUpperCase();
        words[i] = words[i].replace((words[i])[0], lettersUp);
    }
    return words.join(" ");
 }

Regexes are the way to go, though. Please try and use though.

Coder
  • 11
  • 2
0

Keep it as simple as possible - there's no need for additional variables such as lettersUp, you can simply manipulate the strings in the words array.

function titleCase(str) {
  var words = str.split(' ');
  for (var i = 0; i < words.length; i++) {
    words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);     
  }
  return words.join(' '); 
}
Dan Nagle
  • 4,384
  • 1
  • 16
  • 28