我试图写一个函数,大写字符串中每个单词的第一个字母(将字符串转换为标题情况)。

例如,当输入是“我是一个小茶壶”时,我期望“我是一个小茶壶”是输出。然而,该函数返回“i'm a little tea pot”。

这是我的代码:

函数标题案例(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(“ ”); } 返回 str; } console.log(titleCase(“I'm a Little Teapot”));


当前回答

如果可行,请使用text-transform: capitalize;CSS属性将文本转换为标题大小写。

如果您可以同样依赖CSS来实现相同的结果,那么与JavaScript选项相比,这种操作成本更低。

《我是一个小茶壶》是以下片段的结果。

<p style="text-transform: capitalize;">I'm a little tea pot</p>

其他回答

function titleCase(str) { //First of all, lets make all the characters lower case let lowerCaseString = ""; for (let i = 0; i < str.length; i++) { lowerCaseString = lowerCaseString + str[i].toLowerCase(); } //Now lets make the first character in the string and the character after the empty character upper case and leave therest as it is let i = 0; let upperCaseString = ""; while (i < lowerCaseString.length) { if (i == 0) { upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase(); } else if (lowerCaseString[i - 1] == " ") { upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase(); } else { upperCaseString = upperCaseString + lowerCaseString[i]; } i = i + 1; } console.log(upperCaseString); return upperCaseString; } titleCase("hello woRLD");

ECMA2017或ES8

const titleCase = (string) => { return string .split(' ') .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length)) .join(' '); }; let result = titleCase('test test test'); console.log(result); Explanation: 1. First, we pass the string "test test test" to our function "titleCase". 2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"] 3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it. 4. In the last, we join the array using space as we split the string by sapce.

你把复杂变得很简单了。你可以在你的CSS中添加这个:

.capitalize {
    text-transform: capitalize;
}

在JavaScript中,可以将类添加到元素中

 document.getElementById("element").className = "capitalize";

Let cap = (str) => { Let arr = str.split(' '); 加勒比海盗。forEach(函数(项,索引){ Arr [index] = item。替换(项目[0],[0].toUpperCase ()); }); 加勒比海盗。加入(' '); }; console.log(cap(“我是一个小茶壶”));

快速可读版本参见基准http://jsben.ch/k3JVz

text-transform: capitalize;

CSS已经得到了它:)