anytimesoon
anytimesoon

Reputation: 3

Counter variable in for/in loops

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?

Upvotes: 0

Views: 101

Answers (1)

KmasterYC
KmasterYC

Reputation: 2354

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);

Upvotes: 2

Related Questions