本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
javascript中没有首字母大写函数。
但我们可以利用slice()、touppercase()、tolowercase()函数和字符串拼接符“+”来设置首字母大写。
实现思想:
使用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有首字母大写函数吗的详细内容。