This introductory code snippet demonstrates the basic syntax for capitalizing the first letter of a string. However, our goal is to apply this concept to each word in a sentence. Let's dive into the details and learn how to
charAt(): Returns the character at the specified index.
toUpperCase(): Converts the character(s) to uppercase.
slice(): Extracts a part of a string and returns it as a new string.
split(): Divides a string into an ordered list of substrates.
Here's a function that applies these steps:
Now, let's extend this logic to every word in a sentence:
In this function, we
split the sentence into words,
map over each word to capitalize the first letter, and then
join them back into a single string.
Let's put our function to the test:
This result shows that our function correctly capitalizes the first letter of each word in the sentence.
You can use the
capitalizeFirstLetter function shown earlier to capitalize the first letter of a string.
How do you capitalize first letter?
Access the first character using
charAt(0), convert it to uppercase, and concatenate it with the rest of the string.
toUpperCase() method to convert any character or string to uppercase.
map function on an array of words, applying the capitalization logic to each word, as demonstrated in the
By integrating these techniques into your coding toolkit, you'll be well-equipped to handle text formatting challenges with ease. Happy coding!
Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.