Sentence Capitalization
Challenge Description
Given a string, capitalize the first letter of each word and make the rest of the letters lowercase. For example:
- "hello world" becomes "Hello World"
- "jordan peterson" becomes "Jordan Peterson"
Tips to Solve
tip
- Make the string lowercase using the
toLowerCasemethod. - Convert the string to an array using the
splitmethod. - Capitalize the first letter of each word using the
mapmethod. - Convert the array back to a string using the
joinmethod.
Step-by-Step Solution
Let's break down the solution into easy steps:
-
Make the String Lowercase: Use the
toLowerCasemethod to convert the entire string to lowercase.const lowerCaseStr = "HELLO WORLD".toLowerCase(); // "hello world" -
Convert the String to an Array: Use the
splitmethod to convert the string into an array of words.const wordsArray = lowerCaseStr.split(" "); // ["hello", "world"] -
Capitalize Each Word: Use the
mapmethod to capitalize the first letter of each word.const capitalizedWordsArray = wordsArray.map(
(word) => word[0].toUpperCase() + word.slice(1)
); // ["Hello", "World"] -
Convert the Array Back to a String: Use the
joinmethod to combine the words back into a single string.const capitalizedStr = capitalizedWordsArray.join(" "); // "Hello World"
Full Solution Code
Here is the complete solution using the steps above:
const capitalize = (str) => {
return str
.toLowerCase()
.split(" ")
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(" ");
};
console.log(capitalize("hello world")); // Output: "Hello World"
console.log(capitalize("zeeshan mukhtar")); // Output: "Zeeshan Mukhtar"