When dealing with strings, it often becomes necessary to capitalize the first letter, preserving the case of the remaining characters. This article delves into how to accomplish this task efficiently in JavaScript.
One straightforward approach involves extracting the first character of the string, converting it to uppercase, and concatenating it with the remaining substring. This can be achieved using the following function:
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
For example, calling capitalizeFirstLetter("this is a test") would return "This is a test".
While some previous versions of this answer suggested modifying String.prototype, it's generally not recommended for maintainability reasons. Adding a function to the prototype makes it challenging to pinpoint where it originated and may lead to conflicts with other code.
The above is the detailed content of How Can I Capitalize the First Letter of a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!