In JavaScript, you can make the first letter of a string uppercase using the charAt()
, toUpperCase()
, and slice()
methods. Here is an example code snippet:
pythonlet str = "hello world";
str = str.charAt(0).toUpperCase() + str.slice(1);
console.log(str);
In this code, the charAt()
method is used to get the first character of the string, which is then converted to uppercase using the toUpperCase()
method. The slice()
method is used to get the remaining part of the string from the second character onwards. Finally, the uppercase first character and the remaining string are concatenated using the +
operator and assigned back to the str
variable.
The output of this code will be:
Hello world
This method only makes the first letter of the string uppercase. If you want to make all the words in a string start with uppercase, you can use the split()
and map()
methods along with this method. Here is an example code snippet:
pythonlet str = "hello world";
str = str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
console.log(str);
In this code, the split()
method is used to split the string into an array of words, the map()
method is used to apply the first letter uppercase transformation to each word in the array, and the join()
method is used to concatenate the modified words back into a string.
The output of this code will be:
Hello World
Comments
Post a Comment