To capitalize the first letter of a string in JavaScript, you can use this simple function:
โ Example:
๐ 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
โ 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.