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

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

Linda Hamilton
Release: 2024-12-16 04:30:14
Original
636 people have browsed it

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:

  • "this is a test" should become "This is a test"
  • "the Eiffel Tower" should become "The Eiffel Tower"
  • "/index.html" should remain unchanged

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

This function employs two string methods:

  • charAt(0) retrieves the first character of the input string.
  • slice(1) creates a new string containing all characters except the first.

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!

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