javascript中没有首字母大写函数;但可以利用slice()、toUpperCase()、toLowerCase()函数和字符串拼接符“+”来设置首字母大写,确保字符串的首字母是大写,其余部分为小写。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript中没有首字母大写函数。
但我们可以利用slice()、toUpperCase()、toLowerCase()函数和字符串拼接符“+”来设置首字母大写。
实现思想:
实现代码:
function f(str) {
newStr = str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase();
console.log(newStr);
}
f("hello World!");
改进一下,让字符串中每个单词的首字符都大写
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!");
【相关推荐:javascript学习教程】
以上就是javascript有首字母大写函数吗的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!