Capitalize each word in the string separated by a space

  • 2020-03-30 02:33:54
  • OfStack

In a string, each word is separated by an unlimited number of Spaces
 
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" 

Notice the key line in the code
 
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); 

Words [I].charat (0).touppercase () just takes the first letter of the string and converts it toUpperCase. It doesn't change the original string, so you need to concatenate other characters in the original string and assign the new value to the original string

Related articles: