如何使用JavaScript将字符串中每个单词的首字母大写? [英] How can I capitalize the first letter of each word in a string using JavaScript?
本文介绍了如何使用JavaScript将字符串中每个单词的首字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数,该函数将字符串中每个单词的首字母大写(将字符串转换为标题大小写).
I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).
例如,当输入为我是小茶壶"
时,我希望我是小茶壶"
是输出.但是,该函数返回我是个小茶壶"
.
For instance, when the input is "I'm a little tea pot"
, I expect "I'm A Little Tea Pot"
to be the output. However, the function returns "i'm a little tea pot"
.
这是我的代码:
function titleCase(str) {
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(" ");
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
推荐答案
您正在使复杂的事情变得非常容易.您可以在CSS中添加它:
You are making complex a very easy thing. You can add this in your CSS:
.capitalize {
text-transform: capitalize;
}
在JavaScript中,您可以将类添加到元素
In JavaScript, you can add the class to an element
document.getElementById("element").className = "capitalize";
这篇关于如何使用JavaScript将字符串中每个单词的首字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文