Reputation: 89
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
Upvotes: 4
Views: 993
Reputation: 2862
you can write up a function that does the job for u,as below
function capsFirstLetter(str){
return str.substr(0,1).toUpperCase()+str.substr(1);
}
capsFirstLetter("hello") // Hello
or you can add the method in the String class and using it for all the string instances
String.prototype.capsFirstLetter = function(){
return this.substr(0,1).toUpperCase() + this.substr(1);
}
"hello".capsFirstLetter() // "Hello"
Upvotes: 1
Reputation: 1073978
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);
Upvotes: 10
Reputation: 11721
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);
};
Upvotes: 2