This article mainly introduces how to change the first letter of each word in a string to uppercase. For more information, see the following strings. Each word is separated by a space and the number of spaces is unlimited.
The Code is as follows:
Function capitalize (sting ){
Var words = string. split ("");
For (var I = 0; I <words. length; I ++ ){
Words [I] = words [I]. charAt (0). toUpperCase () + words [I]. slice (1 );
}
Return words. join ("");
}
Var string = "ajax cookie event object ";
Capitalize (string); // "Ajax Cookie Event Object"
Pay attention to the key sentence in the code
The Code is as follows:
Words [I] = words [I]. charAt (0). toUpperCase () + words [I]. slice (1 );
Words [I]. charAt (0 ). toUpperCase () only obtains the first letter of the string and converts it to an uppercase letter. It does not change the original string. Therefore, it must be connected to other characters in the original string and the new value must be assigned to the original string.