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
toLowerCase
method. - Convert the string to an array using the
split
method. - Capitalize the first letter of each word using the
map
method. - Convert the array back to a string using the
join
method.
Step-by-Step Solution
Let's break down the solution into easy steps:
-
Make the String Lowercase: Use the
toLowerCase
method to convert the entire string to lowercase.const lowerCaseStr = "HELLO WORLD".toLowerCase(); // "hello world"
-
Convert the String to an Array: Use the
split
method to convert the string into an array of words.const wordsArray = lowerCaseStr.split(" "); // ["hello", "world"]
-
Capitalize Each Word: Use the
map
method 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
join
method 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"