Home > Web Front-end > Front-end Q&A > Does javascript have a function to capitalize the first letter?

Does javascript have a function to capitalize the first letter?

青灯夜游
Release: 2022-02-18 17:34:46
Original
3032 people have browsed it

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.

Does javascript have a function to capitalize the first letter?

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

Does javascript have a function to capitalize the first letter?

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

Does javascript have a function to capitalize the first letter?

[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!

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