I want to use a javascript function to capitalize the first letter of every word
eg:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> Th
This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.
function capitalize(str){
var strArr = str.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1);
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
"tHiS iS a tESt".replace(/[^\s]+/g, function(str){
return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
});
Other variant:
"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){
return $1.toUpperCase()+$2.toLowerCase();
});