0

The function here's suppose to capitalize the beginning of every word. I know there are other simpler solutions out there, but I'm a little stubborn with why this one isn't working properly. Its tacking an "undefined" after my return every time.

function LetterCapitalize(str) { 

  var c = str[0].charCodeAt(0);
  var letter;
  var result = "";

  if( (c >= "a".charCodeAt(0) && c <="z".charCodeAt(0)) || (c >= "A".charCodeAt(0) && c <="Z".charCodeAt(0)))
  {
    result = str[0].toUpperCase()
  }
  else
  {
    result += str[i];
  }

  for(var i=1; i<=str.length; i++)
  {
        if(str[i-1] == " ")
        {
            letter = str[i].toUpperCase()
            result += letter;
        }
        else
        {
            result += str[i];
        }
  }
       return result; 
}
jchi2241
  • 2,032
  • 1
  • 25
  • 49

1 Answers1

0

If you change

for(var i = 1; i <= str.length; i++)

to

for(var i = 1; i < str.length; i++)

it will work as you expect. As it stands you are indexing into the string one extra time which will return undefined.

Also the first if/else statement can be ditched altogether. The else statement would be a syntax error anyway with i is undefined

awbergs
  • 942
  • 4
  • 15