Last Updated : Sep 26, 2023
Capitalizing a string's first letter is an ordinary task in string manipulation.
While there are a number of ways to accomplish this, in this lesson we'll focus on utilising regular expressions to capitalize the first letter of a string.
Regular expressions are a useful tool in string manipulation jobs because they offer a clear and effective approach to work with similarities in strings.
A string of characters known as a regular expression (regex) creates a search pattern.
Replace given string first letter to its uppercase version by finding first letter using regex pattern.
Let's move on to the section of code where we will apply this technique.
- The str parameter is the only one required by the capitalize() method, which is declared. The first letter of the input string will be capitalized by this function.
- The function substitutes the capitalized initial letter for a pattern in the input string (str) using the str.replace() method.
- The search pattern in the replace() method is the regular expression /(.)/. The string's beginning is indicated by a caret, and any character is represented by the period (.). Therefore, the first character in the string's beginning is matched by this pattern.
- The replace() method's second argument is an arrow function with the two arguments match and firstLetter. The firstLetter parameter holds the first letter recognised by the regular expression, while the match parameter holds the complete matched substring (in this example, the first character).
- The first letter is changed to uppercase inside the arrow function using firstLetter.toUpperCase(). The input string's initial letter will be capitalized as a result.
- The updated text with the first letter capitalized is what the replace() function produces.
- Input is passed as an argument to the capitalize() method, and the returned value is saved in the const variable output.
- For printing capitalized string, we use the statement console.log(output).
By combining the replace method with regular expressions, which are strong tools for matching patterns and modification, we successfully produced the intended outcome.
Understanding regular expressions gives up a world of opportunities for string manipulation tasks, and knowing how to capitalize the initial letter of a string is a common necessity in many applications.