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

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

DDD
Release: 2024-12-30 04:09:10
Original
331 people have browsed it

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

Capitalizing the First Letter of a String in JavaScript

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.

A Solution Using Character Manipulation

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

For example, calling capitalizeFirstLetter("this is a test") would return "This is a test".

Why Not Modify String.prototype?

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template