String [0] .toUpperCase () does not return the expected results?

I am trying to use the first letter in every 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 problem that I see is that when I try to assign aWord [0] to its capital value, no assignment happens? How do I change this so that an appointment occurs?

PS. I know there is 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 got it yet! as such, any advice that is not related to regular expression is greatly appreciated.

+4
source share
3 answers

Strings are immutable, so this will do nothing:

aWord[0]=aWord[0].toUpperCase();

:

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);
+10

aWord[0] char, char char, 'a' = 'b'

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);
};
+2

you can write a function that does the job for u as shown below

function capsFirstLetter(str){
return str.substr(0,1).toUpperCase()+str.substr(1);

}
capsFirstLetter("hello") // Hello

or you can add a method to the String class and use it for all string instances

   String.prototype.capsFirstLetter = function(){
       return this.substr(0,1).toUpperCase() + this.substr(1);
    } 
 "hello".capsFirstLetter() // "Hello"
+1
source

Source: https://habr.com/ru/post/1611730/


All Articles