Javascript Capitalize First Letter

To capitalize the first letter of a string in JavaScript, you can use this simple function:

function capitalizeFirstLetter(str) {
if
(!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1);
}

✅ Example:

console.log(capitalizeFirstLetter("hello")); // Output: "Hello"
console.log(capitalizeFirstLetter("javaScript")); // Output: "JavaScript"

📌 How it works:

  • str.charAt(0).toUpperCase() → Capitalizes the first character.

  • str.slice(1) → Gets the rest of the string starting from the second character.

  • The two parts are concatenated.

To capitalize the first letter of each word in a string

To capitalize the first letter of each word in a string (also called title case) in JavaScript, you can use this function:
function capitalizeEachWord(str) {
return str
.split(‘ ‘)
.map(word =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
)
.join(‘ ‘);
}

✅ Example:

console.log(capitalizeEachWord(“hello world”));
// Output: “Hello World”

console.log(capitalizeEachWord(“javaScript is awesome”));
// Output: “Javascript Is Awesome”

🔍 How it works:

  • split(' ') → Splits the string into an array of words.

  • map(...) → Capitalizes the first letter of each word.

  • join(' ') → Joins the capitalized words back into a single string.

Also Read : MP B.Ed Allotment Letter for 2025 Download

Be the first to comment

Leave a Reply