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

例如,当输入是“我是一个小茶壶”时,我期望“我是一个小茶壶”是输出。然而,该函数返回“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”));


当前回答

我认为这条路会快一些;因为它不会拆分字符串并重新连接;只是用正则表达式。

var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());

解释:

(^\w{1}):匹配字符串的第一个字符 |:或者 (\s{1}\w{1}):匹配一个空格后面的一个字符 G:全部匹配 match => match. touppercase (): replace with can take function, so;将匹配替换为大写匹配

其他回答

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.

ECMAScript 6版本:

const toTitleCase =(短语)=> { 返回的短语 .toLowerCase () .split (' ') .map(word => word. charat (0).toUpperCase() + word.slice(1)) . join (' '); }; let result = toTitleCase('maRy have a lIttLe LaMb'); console.log(结果);

这是一个使用现代javascript实践来提高可读性的完美例子。还没有看到一个减少版本在这里,但这是我使用的。这既是一个咖喱单行和非常可读

sentence
    .trim().toLowerCase()
    .split(' ')
    .reduce((sentence, word) => `${sentence} ${word[0].toUpperCase()}${word.substring(1)}`, '')
    .trim()

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

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

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

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

这里我使用了三个函数toLowerCase(), toUpperCase()和replace(regex,replacer)

function titleCase(str) { 
     return str.toLowerCase().replace(/^(\w)|\s(\w)/g, (grp) => grp.toUpperCase()); 
}

titleCase(“我是一个小茶壶”);