JavaScript titleCase函数 [英] JavaScript titleCase function
问题描述
function titleCase(str) {
str.toLowerCase();
var strAr = str.split(" ");
for (var i = 0; i < strAr.length; i++) {
strAr[i].charAt(0).toUpperCase();
}
str = strAr.join(" ");
return str;
}
titleCase("I'm a little tea pot");
我正在尝试创建一个函数,它接受一个字符串并返回一个包含所有第一个字符串的字符串一个大写的单词,其余的小写单词
I am trying to make a function that takes a string and return a string with all the first latters of a word in uppercase and the rest in lowercase
例如:我的名字是nikos - >我的名字是Nikos
For example: My name is nikos --> My Name Is Nikos
我无法理解为什么上面的代码不起作用...... :(
I can't understand why the code above is not working...:(
推荐答案
你需要做的你的字符串的赋值,所以第一个大写字母,然后字符串的其余部分为小写:
You will need to do an assignment for your string, so the first capital letter then the rest of the string as a lowercase:
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].substring(1).toLowerCase();
注意值 strAr [i] .charAt(0).toUpperCase()
只会将第一个字符作为大写字母返回,它不会实际上以任何方式更改字符串。
Note the value strAr[i].charAt(0).toUpperCase()
will only return the first character as a capital letter, it will not actually change the string in any way.
这篇关于JavaScript titleCase函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!