0

This is my first time posting here, and I'm very new to coding.

I am trying to capitalise the first letter in each word of any given string. I've split the string into separate letters, and used a for/in loop to go through each letter.

Here's what I have so far:

function LetterCapitalize(str) {

  var split = str.split('');

  for (var i in split) {
    if (i === 0) {
      split[i] = split[i].toUpperCase();
    } else if (split[i] === " ") {
      split[i+1] = split[i+1].toUpperCase();
    }
  }

  str = split.join('');

  return str;

}

console.log(LetterCapitalize('hello world'));

I keep getting an error 'Uncaught TypeError: Cannot read property 'toUpperCase' of undefined'

What am I doing wrong. What's a better way of doing what I'm trying to do?

  • 1
    Another option, you could use CSS instead, with `text-transform: capitalize;` :) – Andy-Delosdos Aug 20 '16 at 12:27
  • 2
    [Don't use `for...in` with arrays](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea). `i` is a string so at index 5 you get `"5"+1 === "51"`. – JJJ Aug 20 '16 at 12:30
  • Haha, yes! This was meant as more of a javascript thought-exercise to help me learn the language, CSS would be cheating :) – anytimesoon Aug 20 '16 at 12:31
  • @Juhana That's very interesting. I'll have a read through that link – anytimesoon Aug 20 '16 at 12:33
  • 1
    Possible duplicate of [Convert string to title case with javascript](http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – DavidDomain Aug 20 '16 at 12:44

1 Answers1

2

Check it out!

var str = 'i am a string';
var arr = str.split(' ');

var final_str = arr.map(function (item) {
    return item[0].toUpperCase()+item.slice(1);
}).join(' ');

console.log(final_str);
KmasterYC
  • 2,294
  • 11
  • 19
  • This looks great, but I'm not sure I understand how str is passed to final_str. Does this need to be done separately? – anytimesoon Aug 20 '16 at 15:16
  • To get final_str from array of words you must do 2 steps. First go through each element and capitalize it => So you get new array of capitalize words. Second you must join all processed-element with space character – KmasterYC Aug 20 '16 at 15:36
  • And of course, you can seperate map and join function – KmasterYC Aug 20 '16 at 15:36