Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string[0].toUpperCase() not returning expected results?

Tags:

javascript

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

like image 502
YOO629 Avatar asked Dec 10 '22 20:12

YOO629


2 Answers

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);
like image 62
T.J. Crowder Avatar answered Dec 13 '22 10:12

T.J. Crowder


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);
};
like image 33
Catalin Avatar answered Dec 13 '22 09:12

Catalin