Javascript – Capitalize First letter of Each Word in a String

  • by
javascript-capitalize-first-letter-of-a-string

There are multiple ways of Capitalizing the first letter of each word in a given string or a sentence. This post shows several ways to achieve this and also shows to handle in between spaces in a sentence to eliminate it. (Example: Javascript is the langauge of Internet => Javascript Is The Language Of Internet). So let’s explore.

Javascript – Capitalizing First letter of a word:

To only capitalize first letter of a word, we can simply use:

let finalName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();

This can be useful when we want to capitalize a name or a noun in a string.

Example:

let name = 'javascript';
console.log(name.charAt(0).toUpperCase() + name.slice(1).toLowerCase());

Output:

Javascript

To check if a string is a sentence or just a word without any spaces and capitalize first letter of it, we can check if it contains spaces using javascript’s includes function and then using foreach loop we can capitalize each word after spaces.

Example:

function capitalizeName(name) {
if (name.includes(" ")) {
let names = name.split(" ");
names.forEach(element => {
names[names.indexOf(element)] = element.charAt(0).toUpperCase() + element.slice(1).toLowerCase();
});
return names.join(" ");
}
else
return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
}

console.log(capitalizeName("javascript is the language of internet"));
console.log(capitalizeName("nodejs"));

Output:

Javascript Is The Language Of Internet
Nodejs

Using Array.map() function to capitalize first letter of a string:

We can also use Javascript Array.map function to achieve the functionality. We can first split our input string using a char. In this case we can use a WhiteSpace to split our string. And using map() function on this array. Later join the created array of words using javascript join function.

Example:

let text = "javascript is the language of internet";

let capitalizeText = text.split(' ').map(t => t.charAt(0).toUpperCase() + t.slice(1).toLowerCase()).join(" ");

console.log(capitalizeText);

Output:

Javascript Is The Language Of Internet

Snapshot:

javascript-capitalize-first-letter-of-a-string

Thank you.