Home > Web Front-end > JS Tutorial > How Can I Capitalize Only the First Letter of a String in JavaScript?

How Can I Capitalize Only the First Letter of a String in JavaScript?

Linda Hamilton
Release: 2024-12-29 01:10:11
Original
719 people have browsed it

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template