I am trying to capitalize the first letter in each word in a string. My code is as follows:
function LetterCapitalize(str)
{
var words=str.split(" ");
var newArray=[];
for(i=0; i<words.length; i++)
{
var aWord=words[i];
//this line below doesn't work...don't know why!
aWord[0]=aWord[0].toUpperCase();
newArray.push(aWord);
};
newArray.join(" ");
return newArray;
};
So the issue I'm seeing is that when I try to assign aWord[0] to its uppercase value, the assignment doesn't happen? How do I modify this so that the assignment happens?
PS. I know there's a regular expression method that can do this in one fell swoop, but I just picked up javascript a few days ago and haven't gotten that far yet! as such, any tips that don't involve regexp are greatly appreciated
Strings are immutable, so this won't do anything:
aWord[0]=aWord[0].toUpperCase();
Instead, you have to create a new string:
aWord = aWord.substring(0, 1).toUpperCase() + aWord.substring(1);
// or:
aWord = aWord.charAt(0).toUpperCase() + aWord.substring(1);
// or on *most* engines (all modern ones):
aWord = aWord[0].toUpperCase() + aWord.substring(1);
aWord[0]
is a char, and you cannot assign a char a new char, like 'a' = 'b'
Use a variable instead
for(i=0; i<words.length; i++)
{
var aWord=words[i];
//this line below doesn't work...don't know why!
var newChar =aWord[0].toUpperCase();
newArray.push(newChar);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With