Home >Web Front-end >JS Tutorial >How do I Capitalize Only the First Letter of a String in JavaScript?
Capitalizing the First Letter of a String in JavaScript
Question: How can JavaScript be used to capitalize only the first letter of a string, leaving the rest unchanged, regardless of its initial case? For example:
Answer: To effectively capitalize just the first letter of a string, JavaScript provides an elegant solution through its capitalizeFirstLetter function:
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
This function employs two string methods:
The result combines the capitalized first character with the original string, effectively capitalizing only the initial letter. Unlike modifying String.prototype, this approach offers enhanced maintainability by avoiding potential conflicts.
The above is the detailed content of How do I Capitalize Only the First Letter of a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!