Home >Web Front-end >JS Tutorial >How Can I Capitalize Only the First Letter of a String in JavaScript?
Capitalizing the First Letter of a String in JavaScript
In JavaScript, there may arise a need to capitalize the first character of a string while preserving the case of the remaining letters. Consider the following examples:
"this is a test" → "This is a test"
"the Eiffel Tower" → "The Eiffel Tower"
"/index.html" → "/index.html"
To accomplish this task, a JavaScript function can be employed:
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
This function takes a string as its input and uppercases its first character using charAt(0). toUpperCase(). The remaining characters are preserved by slicing the string starting from the second character using slice(1).
By utilizing this function, you can effectively transform the initial character of a string to uppercase while maintaining the case of the subsequent letters.
The above is the detailed content of How Can I Capitalize Only the First Letter of a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!