本教程操作环境:windows10系统、javascript1.8.5版、dell g3电脑。
javascript怎么实现首字母大写在javascript中,可以使用slice()方法、touppercase()方法和tolowercase()方法来设置首字母大写,确保字符串的首字母都大写,其余部分小写。
步骤:
● 使用slice()方法将字符串分成两部分:首字母字符部分,和其他子字符部分。
● 使用touppercase()方法将首字母转换为大写;使用tolowercase()将其他子字符转换为小写。
● 使用“+”运算符,将两个部分重新拼接起来
示例1:
function titlecase(str) {newstr = str.slice(0,1).touppercase() +str.slice(1).tolowercase(); return newstr;} titlecase("hello world!");
输出:
hello world!
示例2:让字符串的每个单词首字母都大写,其余部分小写
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'm a little tea pot");
输出:
i'm a little tea pot
相关推荐:javascript学习教程
以上就是javascript怎么实现首字母大写的详细内容。