0

I've been trying for the last hours to understand why my code is not working well. Instead of capitalizing only the first letters of each item in the array my code capitalizes all the letters in the array.

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

  for (var i = 0; i < str.length; i++){
    str[i] = str[i].split(' ');
    str[i][0] = str[i][0].toUpperCase(); 
    str[i] = str[i].join(' ');
  }
  return str.join(' ');
}

titleCase("I'm a little tea pot");
Ozan
  • 1,623
  • 3
  • 13
  • 25
  • Instead of trying for hours, all you had to do was type the title of your question into [Google](https://www.google.com/search?q=site%3Astackoverflow.com+How+to+capitalize+the+first+letter+of+each+word+in+an+array+in+JavaScript&gws_rd=ssl). –  Apr 22 '16 at 01:30
  • I did but the point is that I don't seem to figure out why it is capitalizing all the letters rather than the first ones eve though I am point [0]. – Ozan Apr 22 '16 at 01:32
  • First, the `.split()` in the loop doesn't really make sense since you've already split on a space character, which means each word won't have a space. Since the result of `.split()` is an Array, and you've overwritten the string at `str[i]` with that Array, index `0` will be just giving you back the original string. If you were trying to mutate the first character of the string, that won't work because strings are immutable in JS. –  Apr 22 '16 at 01:34

2 Answers2

1

If you want a more functional way:

const titleCase = str => (
  str.split(' ').map(c => c.slice(0, 1).toUpperCase() + c.slice(1)).join(' ')
);

titleCase("I'm a little tea pot");
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • How can this be javascript? Your '=>' object notation is from PHP. – russellmania Apr 28 '16 at 00:47
  • @ruzel copy and paste that on Chrome, or Firefox or Edge and you'll see it's working! It's the new version of Javascript, ES6. And this `=>` are called [Arrow Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Buzinas Apr 28 '16 at 00:49
  • Oh! Good to know. Hadn't made the transition yet. – russellmania Apr 28 '16 at 22:48
0

Try:

function titleCase(str)
{
    return str.replace(/\w\S*/g, function(txt) { 
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
andrew
  • 9,313
  • 7
  • 30
  • 61
Matt Komarnicki
  • 5,198
  • 7
  • 40
  • 92