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

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

其他回答

text-transform: capitalize;

CSS已经得到了它:)

或者可以使用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");

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

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

ECMAScript 6版本:

title
    .split(/ /g).map(word =>
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join(" ");

原始代码:

function capi(str) {
    var s2 = str.trim().toLowerCase().split(' ');
    var s3 = [];
    s2.forEach(function(elem, i) {
        s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
    });
    return s3.join(' ');
}
capi('JavaScript string exasd');