In a string, each word is separated by a space, and the number of spaces is unlimited.
The code copy 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 copy is as follows:
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
words[i].charAt(0).toUpperCase() just gets the first letter of the string and converts it to capital letters. It does not change the original string, so it needs to be concatenated with other characters in the original string and will Assign new value to the original string