Learn how to capitalize first letter of string in javascript.
There are different ways through which we can uppercase the first letter of the string in javascript.
Slicing the string in two parts to make string capitalized.
We will slice the first letter of the string and make it uppercase then join it with the rest of the string and return it.
let str = 'prashant'; let capitalized = str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalized); //'Prashant'
charAt(index) returns the character at the given index. As strings are zero-index based and characters of it can be accessed just like an array element we can use that as well str[0]
, but it work on IE9 and less.
By splitting the string into an array of characters.
We can split the string into an array of characters and then make the first character uppercase and join them again to form the capitalized string.
let str = 'prashant'; let arr = str.split(''); arr[0] = arr[0].toUpperCase(); let capitalized = arr.join(''); console.log(capitalized); //'Prashant'
We can wrap them inside a function to return the capitalized string.
let capitalized = (str) => { //If not string then return empty string if (typeof str !== 'string') { return ''; } //Return the capitalized string return str.charAt(0).toUpperCase() + str.slice(1); } or let capitalized = (str) => { //If not string then return empty string if (typeof str !== 'string') { return ''; } //Return the capitalized string let arr = str.split(''); arr[0] = arr[0].toUpperCase(); return arr.join(''); }
Note:- If you want to just capitalize the first letter of the string for design purpose then it better to use the CSS style property to do the same.
<div class="capitalize" >prashant<div> .capitalize{ text-transform: capitalize; }