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

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


当前回答

也是一个很好的选择(特别是如果你使用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(" ");
}

其他回答

这里我使用了replace()函数。

function titleCase(str){
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
/* 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(“我是一个小茶壶”);

这是你可以用map函数做的,它做的和接受的答案一样,但是没有for循环。因此,可以节省几行代码。

函数titleCase(text) { If (!text)返回文本; If (typeof text !== 'string')抛出"无效参数"; 返回text.toLowerCase()。(' ')。Map (value => { return value.charAt(0).toUpperCase() + value.substring(1); })。加入(' '); } console.log(titleCase(“我是一个小茶壶”));

如果您可以使用第三方库,那么Lodash为您提供了一个帮助函数。

https://lodash.com/docs/4.17.3#startCase

_。startCase (foo栏); // => 'Foo Bar' _.startCase(“——foo bar”); // => 'Foo Bar' _.startCase(“fooBar”); // => 'Foo Bar' _.startCase(“__FOO_BAR__”); // => ' foo bar ' < script src = " https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js " > < /脚本>