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

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


当前回答

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

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

其他回答

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 captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')

@somethingthere有一个更紧凑(和现代)的重写方案:

let titleCase = (str => str. tolowercase()。(' ') . map(分裂 c => c. charat (0). touppercase () + c.substring(1))。加入(' ')); 文档。write(titleCase(“我是一个更小的茶壶”));

下面是字符串中每个单词首字母大写的另一种方法。

使用prototype为String对象创建一个自定义方法。

String.prototype.capitalize = function() {
    var c = '';
    var s = this.split(' ');
    for (var i = 0; i < s.length; i++) {
        c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
    }
    return c;
}
var name = "john doe";
document.write(name.capitalize());

这里有一个完整而简单的解决方案:

String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index
  + replacement.length);
}
var str = 'k j g           u              i l  p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === ' ' && str[i+1] !== '')
            str = str.replaceAt(i+1, str[i+1].toUpperCase());
    }
    return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));