In
JavaScript capitalize first letter using charAt (), slice () or toUpperCase () methods. These JavaScript methods can capitalize the first letter of a JavaScript string or the first letter of each word in a JS string. Show
In this review, you will master first letter capitalization in JS with the above methods. Keep reading to see which method fits your current coding project. Contents
How To Capitalize First Letter in JavaScript: Methods To ImplementThe different methods mentioned above offer flexibility regarding letter capitalization in JavaScript. You can turn only the first letter of a string into a capital letter. For example: “this is my car” → “This is my car.” Also, you can use these methods in JavaScript to uppercase first letter of each word in a string. For instance: “this is my car” → “This Is My Car.” It is that simple. However, achieving stellar results requires a deeper understanding of how each method works individually or with similar functions. In this section of our article, we are going to be looking into various ways of capitalizing letters in JavaScript. JavaScript Strings: How To Capitalize First Letter of StringYou can use the toUpperCase () method alone or combine it with the slice () method and charAt () methods to change into uppercase the first letter of a string in JavaScript. – Using toUpperCase () Method AloneThe toUpperCase () method will capitalize string JavaScript has without changing the contents of the string. However, the technique turns the content of the entire string into capital letters. Remember, strings in JavaScript are immutable. So, after invoking the toUpperCase method, the results will be two strings within the code memory. The resulting strings are the converted string and the original string. – Syntax– Code Example: Capitalize Full Sentenceconst str = ‘How are you!’; This method does not take any parameters. Also, capital letters will remain unchanged. In the example above, H is unchanged. Additionally, the method does not affect special characters, like “!” at the end of the string. Similarly, digits remain unchanged. In the new string, these characters remain in the exact location as they were in the original string. How To Uppercase the First Letter Only Using The toUpperCase() MethodIt takes three steps to uppercase only a single letter of a JavaScript string:
Here, use the index of the string’s first character with substring notation [0] and then capitalize by applying toUpperCase(). In Js, counting starts from zero, meaning that the first position of an array is zero; this also applies to a string. – Code Exampleconst publication = “freeCodeCamp”; To remove the letter (f) from freeCodeCamp, invoke publication[0] as shown in the code example below: const publication = “freeCodeCamp”; Alternatively, you can use the substring() method for the second portion to generate a string consisting of all characters except the first. When you run the code, it will return a capital F rather than a small f. If you want to get the entire word back, run the code below: const publication = “freeCodeCamp”; This action concatenates the capital “F” with “reeCodeCamp,” giving rise to the word “FreeCodeCamp.” It uses the ‘+’ operator to combine the two strings. JavaScript Capitalize First Letter: Combining the Three MethodsYou can combine the three methods in JavaScript to uppercase first letter of a JS string. But first, let’s define the remaining two methods – slice () and charAt (). – charAt() MethodThe JS charAt() methods returns a character at a specified position/index in a string. – SyntaxAn index is an integer between “0” and stringName.length -1. If no index is provided or the index cannot be converted to the integer, the default value is ‘0’; thus, returning the first character of str. – Code Exampleconst str = ‘cow dung’; This code example displays a character at the first position of a string. Remember, characters are indexed from left to right in a string, and the first character index is usually 0 while the last character is stringName.length – 1. – The Slice() MethodThe slice() method in JavaScript extracts a portion of a string and returns the extracted portion in a new string without changing the original string. Typically, the slice() function slices a string from a specified between two specified points (start and endpoints). The start and endpoints represent the index items within that array. – SyntaxThe start point is an optional, zero-based index and indicates where to start the extraction process. You can use a negative index, indicating an offset from the end of the sequence. When the start is undefined, the slice will begin from index ‘0’. By contrast, if the start is greater than the index range of the sequence, it returns an empty array. Similarly, the end is optional and is a zero-based index before the point of the end of extraction. Slice () function extracts, up to but not including, end. For instance, slice(1, 5) extracts elements indexed 1,2,3 and 4. You can use a negative index, too, indicating an offset from the end of the sequence. When you omit end, slice () extracts through the end of the sequence. – Code Examplelet text = “cow dung!”; – The Three Functions Code Exampleconst str = ‘cowdung’; The code’s output above shows how easy it is to combine the three methods to uppercase the first letter of a JavaScript string. When you want to capitalize first letter of string JavaScript lets you use the above-mentioned methods. However, it is slightly different when you want to capitalize the first letters of each word in a JavaScript string. Check out the code example: const str = ‘welcome friend, how have you been?’; Here is how to go about it and capitalize each letter of each word yourself: – Split the String Into Separate WordsIt is easier to manipulate each word when you split the string into an array of words, and you can use the split() method to do that. This method takes a string object and splits it according to the characters provided. In this instance, pass the empty space character(‘’) as the value to perform the split. This action returns an array of all the words in the string together with their special characters and digits. That implies there will be an entry in the array for every portion of the string that is separated by a space character. This how the code will appear: const strToArr = str.split(‘ ‘); Most of the tokens are words; however, the comma after “friend” and a question mark after “been” are considered as part of the word. The reason for this is we command split() to separate values according to spaces in between the words. – Iterate Through the Array and Uppercase Every First CharacterLoop through the array and work with each string. Like in the previous section, take the first character of every single string using the first index ([0]) and then combine them with the remainder of the string obtained from the substring() method. Let’s view a coding example of how we did this: const allFirstToUC = strToArr.map(word => word[0].toUpperCase() + word.substring(1)); This is still an array, not a string; you must combine the words to form a sentence. – Recombine the Array Into a Single StringIn this step, you will put the arrays of substrings back together and re-insert the space characters that the split() method removed. To put the words together, JavaScript offers the method join(). The join() method can return an array as a string as it takes a separator as an argument. Note that you can specify what to add between the words. The function takes a character to interject into the array of substrings and uses the same character to combine the array elements back into a single string. To get the initial sentence structure, you will need to pass in the empty space character as a parameter, join(‘’). Here is an example that illustrates this: const newStr = allFirstToUC.join(‘ ‘) See, all the first letters of each word are capitalized in the entire string. Note that there are different methods of iterating through an array. In our code example, we have used the map() method. ConclusionThis uppercase JavaScript tutorial has taught you the following:
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. |