Wednesday, 14 August 2013

Javascript: Capitalizing the beginning of every word.

Javascript: Capitalizing the beginning of every word.

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

No comments:

Post a Comment