JAVASCRIPT
Capitalize First Letter of Each Word (Title Case)
Apply title case to any string in JavaScript by using a regular expression to efficiently capitalize the first letter of every word, useful for names and headlines.
function toTitleCase(inputString) {
if (!inputString) return "";
return inputString.replace(/\b(\w)/g, char => char.toUpperCase());
}
const sentence1 = "hello world from javascript";
const titleCase1 = toTitleCase(sentence1); // "Hello World From Javascript"
const sentence2 = "web development is fun!";
const titleCase2 = toTitleCase(sentence2); // "Web Development Is Fun!"
const sentence3 = "already Title Case?";
const titleCase3 = toTitleCase(sentence3); // "Already Title Case?"
How it works: The `toTitleCase` function takes a string and uses the regex `/\b(\w)/g`. `\b` is a word boundary, which matches the position between a word character and a non-word character (or the start/end of the string). `(\w)` captures the first word character after the boundary. The `g` flag ensures all such occurrences are found. The `replace` method uses a callback function where the captured character (`char`) is converted to uppercase using `toUpperCase()`, effectively capitalizing the first letter of each word in the string.