Let us take a look at this using an example const str = 'i have learned something new today' To achieve this, we split the words from the string and store them in an array, and then use the above concept on each element of the array and join all the array elements together to get the string back. Capitalize the first letter of each word in a string Now what if we want to capitalize the first letters of all the words in a string? Let’s see how we can achieve this as well. const str = 'flexiple' Ĭonst str2 = str.charAt(0).toUpperCase() + str.slice(1) Īs you can see from the above outputs that we have capitalized the first letter of the input string. Now let us use all the three functions together to capitalize the first word of an input string. This function slices a given string from a specified “start” position until the specified “end” position. Now, we would get the remaining characters of the string using the slice() function. To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. In the above example, we see that using the toUpperCase() function on the string converted all the characters of the input string to capital letters.īut this is not what we desire to achieve. The toUpperCase() function converts all the characters of an input string to uppercase The charAt() function returns the character at a given position in a string. To achieve the capitalization of the first letter of a given string in JavaScript, we would use three functions. Capitalize the first letter of each word in a string.Capitalize the first letter of a string.In this tutorial, we shall look at capitalizing the first letter of a string in JavaScript followed by learning how we can capitalize the first letter of each word in a string.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |