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

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


当前回答

/* 1. Transform your string into lower case
   2. Split your string into an array. Notice the white space I'm using for the separator
   3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
      - With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
      - With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
      - The "add" (+) character is for concatenate both strings.
   4. return array.join(' ') // Returns the formatted array like a new string. */


function titleCase(str){
    str = str.toLowerCase();
    var array = str.split(' ');
    for(var c = 0; c < array.length; c++){
        array[c] = array[c][0].toUpperCase() + array[c].substring(1);
    }
    return array.join(' ');
}

titleCase("I'm a little tea pot");

其他回答

或者可以使用replace(),将每个单词的第一个字母替换为“大写”。

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
               return word.replace(word[0], word[0].toUpperCase());
           }).join(' ');
}

titleCase("I'm a little tea pot");

出于可读性考虑,我通常不喜欢使用regexp,而且我也尽量避免使用循环。我认为这是有可读性的。

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};

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

.capitalize {
    text-transform: capitalize;
}

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

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

试试这个函数:

const capitializeName = (name) => {
 
     const splitName = name.split(' ');
        const namesUpper = [];

    for (const n of splitName) {
        namesUpper.push(n[0].toUpperCase() + n.slice(1));
    }
    console.log(namesUpper.join(' '));
};

capitializeName('jahid bhuiyan');

您没有将更改再次分配给数组,因此您的所有努力都是徒劳的。试试这个:

函数titleCase(str) { var splitStr = str.toLowerCase()。分割(' '); For (var I = 0;i < splitStr.length;我+ +){ //你不需要检查i是否大于splitStr长度,就像你的for为你做的那样 //赋值给数组 splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } //直接返回连接的字符串 splitStr返回。加入(' '); } 文档。write(titleCase(“我是一个小茶壶”));