Get the App
SLTechnology News&Howtos  ›  Development  › 

How to capitalize the first letter in javascript

Shulou Source: shulou.com Published: 2022-06-01 10:28:17 10月02日 Update

This article introduces the relevant knowledge of "how to capitalize javascript". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Methods: 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 re-splice the two parts.

The operating environment of this tutorial: windows10 system, javascript1.8.5 version, 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 uppercase to ensure that the first letter of the string is uppercase and the rest of the string is lowercase.

Steps:

● uses the slice () method to divide the string into two parts: the first letter character part and the other subcharacter parts.

● uses the toUpperCase () method to convert the first letter to uppercase and toLowerCase () to convert other subcharacters to lowercase.

● uses the "+" operator to rejoin the two parts

Example 1:

Function titleCase (str) {newStr = str.slice (0Magne1). 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

Tags: Letters methods uppercase characters parts strings lowercase output two content more knowledge examples operators operations practical learned next words dilemma Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Microsoft Linux MariaDB OPPO Reno