Capitalize words [duplicated]

1

I have this code that makes all letters lowercase if the user is capitalized

    function mayusculas(aqui){ 
             var pepe="KarlanKas"; 
    palabras=aqui.value.split(" "); 
    for(a=0;a<palabras.length;a++){ 
        letra=palabras[a].charAt(0); 
        palabras[a] = letra + palabras[a].substring(1 , palabras[a].length).toLowerCase(); 

    } 
    texto=""; 
    for(a=0;a<palabras.length;a++){ 
        if(a>0){texto+=" ";} 
        texto+=palabras[a]; 
    } 
    aqui.value=texto; 
} 

The code works, if I write HELLO, the result is: Hello But if I write: hello, the result is: hello

What I want to do is that the first letter is always capital, the miniscule is already.

    
asked by Jenio158 13.12.2017 в 23:52
source

2 answers

3

You only need to manually put the capital letter and establish that it is only for the first word (first element)

if(a == 0)
    letra=palabras[a].charAt(0).toUpperCase(); 
    
answered by 13.12.2017 / 23:55
source
0

If you are only interested in the first letter in upper case and the rest in lowercase, then another way of doing it would be to convert that first letter to uppercase and then, all the rest to lowercase using slice .

If the rest of the letters you want them as they are written, then you remove .toLowerCase() .

/*función*/

function capitalizeOnlyFirst(string) 
{
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}

/*Hacemos algunas pruebas*/
console.log(capitalizeOnlyFirst('HOLA MUNDO'));
console.log(capitalizeOnlyFirst('HOLA'));
console.log(capitalizeOnlyFirst('hOLA'));
    
answered by 14.12.2017 в 02:05