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

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


当前回答

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

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));

其他回答

最短的一行(也非常快):

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

解释:

^\w:字符串的第一个字符 |:或 \s\w:空格后的第一个字符 (^\w|\s\w)捕捉模式。 g标志:匹配所有出现的情况。


如果你想确保剩下的是小写的:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

使用示例:

几点toTitleCase = str = > str。replace (/ s (^ w | \ \ w) (s *) / g, (m1, m2) = >的m1 toUpperCase () + m2。toLowerCase () 控制台日志。(toTitleCase(“你好世界”);

/* 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");

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

.capitalize {
    text-transform: capitalize;
}

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

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

ES6让

const captilizeAllWords = (sentence) => {
  if (typeof sentence !== "string") return sentence;
  return sentence.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}


captilizeAllWords('Something is going on here')

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

函数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(“我是一个小茶壶”));