1

I basically want to capitalize the first letter in every word in a sentence, assuming that str is all lowercase. So here, I tried to split the string, letter by letter, then by using for loop, I would capitalize whatever the letter that's after a space. Here's my code and could you please point out where I coded wrong? Thank you.

function titleCase(str) {
  var strArray = str.split('');
  strArray[0].toUpperCase();
  for (i=0; i<strArray.length;i++){
    if (strArray[i]===" "){
      strArray[i+1].toUpperCase();
    }
  }
  return strArray.join('');
}
Nah
  • 1,690
  • 2
  • 26
  • 46
yeseula
  • 21
  • 4
  • 1
    This is not a duplicate of that question. This is asking how to capitalize every word's first letter, not just the first letter of a string. – Ahmad Mageed May 11 '18 at 04:05
  • Here you go man: https://stackoverflow.com/questions/32589197/capitalize-first-letter-of-each-word-in-a-string-javascript/32589350 – AndrewL64 May 11 '18 at 04:21

2 Answers2

1

You need to assign the values:

function titleCase(str) {
      var strArray = str.split('');
      strArray[0] = strArray[0].toUpperCase();
      for (i=0; i<strArray.length;i++){
        if (strArray[i]===" "){
          strArray[i+1] = strArray[i+1].toUpperCase();
        }
      }
      return strArray.join('');
    }
Richard Lovell
  • 848
  • 10
  • 18
1

You can try following

function titleCase(str) {
  var strArray = str.split(' ');
  for (i=0; i<strArray.length;i++){
      strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].slice(1);
  }
  return strArray.join(' ');
}


console.log(titleCase("i am a sentence"));
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59