Both of these methods are going to be demonstrated in this article.
Method 1: Using a combination of toUpperCase() and slice()
First of all, create a new string value and store it inside a variable with the help of the following line:
After that, treat this string like an array and fetch the character at the zero indexes and use the toUpperCase() function to make it capitalized:
Make sure to store the return value in a separate variable. Otherwise, it won’t work.
After that, verify that the character stored inside the char1 variable is capitalized by passing it to the console log function:
You will see the following result on the terminal:
It is clear from the output that the first character has been extracted and capitalized. But the original string is yet to be restored.
For that, use the slice method with the argument as 1 to slice the string from index 1 to the very end like
After that, simply create a new variable and call it as resultString and concatenate char1 and remainingString inside it using the following line:
Pass this variable resultString to the console log function to see the outcome:
Executing the program will produce the following output on the terminal:
The final string has the first letter capitalized.
Method 2: Using regex with replace() method and toUpperCase() method
To demonstrate this, create a new string with the following line:
Afterwards, define a regex inside a variable for matching the first character of any string
Here the pattern /^./ defines the first character of any string value
After that, simply use this regExpression in the replace() method. For the second argument, use the same method of fetching the first character and converting it into the uppercase using the toUpperCase() method like
At the end, pass the finalString variable inside the console log function to get the result on the terminal:
Upon execution, this program will produce the following results:
The first character of the string has been successfully capitalized.
To capitalize the first character of any string value, use combinations of string manipulation functions. You can apply two methods. In the first method, toUpperCase() is used to capitalize the first character after it has been fetched from the string and stored inside a new variable. Afterward, the slice() method is used to fetch the remaining string and concatenate the first character and the capitalized first character. In the second method, a regular expression is used to match the string’s first character, and then toUpperCase() is used to capitalize that character.