At first, you need to split() the string on the basis of space and extract the first character using charAt(). Use toUpperCase() for the extracted character.
Example
function capitalizeTheFirstLetterOfEachWord(words) {
var separateWord = words.toLowerCase().split(' ');
for (var i = 0; i < separateWord.length; i++) {
separateWord[i] = separateWord[i].charAt(0).toUpperCase() +
separateWord[i].substring(1);
}
return separateWord.join(' ');
}
console.log(capitalizeTheFirstLetterOfEachWord("my name is john"));To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo43.js.
Output
This will produce the following output with first letter capitalize −
PS C:\Users\Amit\JavaScript-code> node demo43.js My Name Is John