Originally published by Paul Underwood at https://dzone.com
Here is a quick code snippet for the JavaScript version of ucfirst. This code snippet will allow you to capitalize the first letter of a string using JavaScript.
function jsUcfirst(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
This code snippet will use the JavaScript function charAt to get the character at a certain index.
var firstLetter = string.charAt(0);
Next, we use the uppercase function in JavaScript to set this string to be in capitals.
var uppercaseFirstLetter = string.charAt(0).toUpperCase();
Then we can add the rest of the string on to this capital letter by using the function slice() which will allow us to get the rest of the string and remove the first letter.
var stringWithoutFirstLetter = string.slice(1)
Putting this all together, we get the JavaScript ucfirst() alternative.
function jsUcfirst(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
Thanks for reading ❤
If you liked this post, please do share/like it with all of your programming buddies!
Follow us on Facebook | Twitter
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
☞ JavaScript Bootcamp - Build Real World Applications
☞ JavaScript Programming Tutorial - Full JavaScript Course for Beginners
☞ New ES2019 Features Every JavaScript Developer Should Know
☞ Best JavaScript Frameworks, Libraries and Tools to Use in 2019
☞ JavaScript Basics Before You Learn React
#javascript #string