I'll keep this post short and sweet as I gotta run to yoga class soon here! 🧘♂️
No worries though, because capitalizing a word can be done in 1 line of code.
Simple function to return a capitalized word
Does this make sense?
We're just taking the first character and capitalizing it:
str.toUpperCase() and combining that with
str.slice(1), which is just the string with the first character removed.
Great! Now how do I capitalized an entire sentence?
I'd thought you'd ask that! That's slightly more complex but can also be done on 1 line.
Let's first break it up to make it more readable:
Here we are just splitting up the sentence into an array of words, using the
map function to capitalize each word, and then converting the array back into a string. 😆
We can convert this into a 1 line arrow function that should word with any sentence:
const Capitalize = (str) => str .split(' ') .map(word => word.toUpperCase() + word.slice(1)) .join(' ');
Hope this helps!
Did you find this article valuable?
Support Amit Mehta by becoming a sponsor. Any amount is appreciated!