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

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


当前回答

ECMAScript 6版本:

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

其他回答

也是一个很好的选择(特别是如果你使用freeCodeCamp):

function titleCase(str) {
  var wordsArray = str.toLowerCase().split(/\s+/);
  var upperCased = wordsArray.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substr(1);
  });
  return upperCased.join(" ");
}
/* 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");

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

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

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

var str = "hello world"
var result = str.split(" ").map(element => {
    return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);
let string = "I'm a little tea pot";

现在,创建一个以字符串作为参数的函数。

function titleCase(str) {
   return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()).join(" ")
} 

输出

titleCase(string); // "I'm A Little Tea Pot"