Home >Web Front-end >Front-end Q&A >How to capitalize the first letter in javascript

How to capitalize the first letter in javascript

WBOY
WBOYOriginal
2022-03-03 12:00:0133486browse

Method: 1. Use the slice() method to separate the first character of the string; 2. Use the toUpperCase() method to convert the first letter to uppercase; 3. Use the toLowerCase() method to convert other characters to lowercase ;4. Use the " " operator to rejoin the two parts.

How to capitalize the first letter in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How to capitalize the first letter in javascript

In javascript, you can use the slice() method, toUpperCase() method and toLowerCase() method to set the first letter to be capitalized to ensure that the first letter of the string is capitalized All in uppercase, the rest in lowercase.

Steps:

● Use the slice() method to divide the string into two parts: the initial character part, and other sub-character parts.

● Use toUpperCase() method to convert the first letter to uppercase; use toLowerCase() to convert other sub-characters to lowercase.

● Use the " " operator to rejoin the two parts

Example 1:

function titleCase(str) {
newStr = str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase();
    return newStr;
}
 
titleCase("hello World!");

Output:

Hello world!

Example 2: Make the first letter of each word in the string uppercase and the rest lowercase

function titleCase(str) {    var newStr = str.split(" ");    for(var i = 0; i<newStr.length; i++){
        newStr[i] = newStr[i].slice(0,1).toUpperCase() + newStr[i].slice(1).toLowerCase();
    }    return newStr.join(" ");
}
 
titleCase("I&#39;m a little tea pot");

Output:

I'm A Little Tea Pot

Related recommendations: javascript learning tutorial

The above is the detailed content of How to capitalize the first letter in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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