There is no first letter capitalization function in JavaScript; but you can use slice(), toUpperCase(), toLowerCase() functions and the string splicing character " " to set the first letter capitalization to ensure that the first letter of the string is capitalized , the rest is lowercase.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
There are no functions with capital letters in javascript.
But we can use slice(), toUpperCase(), toLowerCase() functions and the string splicing character " " to set the first letter to be capitalized.
Implementation idea:
Use the slice() method to divide the string into two parts: the first letter character part, and other sub-character parts.
Use the toUpperCase() method to convert the first letter to uppercase; use toLowerCase() to convert other subcharacters to lowercase.
Use the " " operator to rejoin the two parts
Implementation code:
function f(str) { newStr = str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase(); console.log(newStr); } f("hello World!");
Improve so that the first character of each word in the string is capitalized
function f(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(); } console.log(newStr.join(" ")); } f("hello World!");
[Related recommendations: JavaScript learning tutorial】
The above is the detailed content of Does javascript have a function to capitalize the first letter?. For more information, please follow other related articles on the PHP Chinese website!