Convert any string to capitalize a string in javascript
Rajnish Katharotiya
Posted on April 12, 2020
Hello JS Devs, Welcome back to a new episode of series called JavaScript useful snippets. In this series, I'm sharing shortcodes and the most common useful functions of javascript. These snippets can help you to make your development more efficient and faster. stay tuned till the end to learn something new... 😊
Javascript Useful Snippets - Capitalize()
In development, it's often that we have to make sure a particular string should be capitalized only - if it's coming from the server, at that time we can use this function. Capitalize() returns a string with the first letter in capital whichever you passed through a parameter. let's look ar the syntax...
const capitalize = ([ first, ...rest ]) => first.toUpperCase() + rest.join('');
Here, this snippet will first destruct string into an array and store the first character into a variable called "first" while all rest characters will be store into the "rest" variable in the form of an array. ( PS: if you found this destruction and ...(three dots before variable) then don't worry, it's a concept of javascript only, you can learn more on detail here .. )
Next in return, this function will do two things; the first one is to convert the "first" character into uppercase ( with default method of javascript called uppercase() ), the second one is to make a string of all array (rest) records by using join. and combines both. let's see what result will look alike...
Result :
const result = ("fooBar") // output: FooBar
As you see, as a result, the first character of string "f" converted into "F" (capital) and the rest of the characters are the same.
Thank you for watching/reading folks, if you found this informative and wanted to make me more content like this please support me on Patreon.
Now, Guys on the next episode I'm going to share a function to get byte size of any given string. so follow/subscribe to get notification...
Subscribe on youtube https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg
Facebook: https://www.facebook.com/KatharotiyaRajnish/
Twitter: https://twitter.com/tutorial_spot
Posted on April 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.