toUpperCase() which can be used to convert the first letter of a string to uppercase.
Here is an example of how to use the
toUpperCase() method to make the first letter of a string uppercase:
let str = "hello world"; let firstLetter = str.charAt(0); let upperFirstLetter = firstLetter.toUpperCase(); let restOfString = str.slice(1); let newString = upperFirstLetter + restOfString; console.log(newString); // Output: "Hello world"
In this example, the
charAt(0) method is used to get the first letter of the string and store it in the
firstLetter variable. The
toUpperCase() method is then used to convert the
firstLetter to uppercase and store it in the
upperFirstLetter variable. The
slice(1) method is then used to get the rest of the string, after the first letter, and store it in the
restOfString variable. Finally, the
restOfString are concatenated together to create a new string with the first letter in uppercase.
Alternatively, a one-liner solution can be achieved by using the following code snippet:
let newString = str.replace(/^\w/, c => c.toUpperCase()); console.log(newString); // Output: "Hello world"
This uses the replace function with regular expression
/^\w/ which matches the first word character of the string and replace it with the uppercase version of that character.
Another way to do this is by using the
let newString = str.substring(0, 1).toUpperCase() + str.substring(1); console.log(newString); // Output: "Hello world"
This creates a new string by taking the first character of the input string and converting it to uppercase, then concatenating it with the rest of the string after the first character.