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

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


当前回答

有很多方法可以实现这一点,例如,你可以尝试遍历字符串,或使用JavaScript内置的split(), map()和join()

我更喜欢使用正则表达式与替换方法,这是可用的字符串

capitalize = (str) =>  {
  return str.replace(/\b[a-z]/g, (letter) => letter.toUpperCase(););
}

使用\b边界匹治程序和[a-z]字符类标识,并使用回调函数将其替换为字母的大写版本。 更高效的 因为它只在字符串中的字符上迭代一次,并且它使用正则表达式来标识要大写的字母,这通常比使用循环和字符串操作实现相同的逻辑更快。

其他回答

@somethingthere有一个更紧凑(和现代)的重写方案:

let titleCase = (str => str. tolowercase()。(' ') . map(分裂 c => c. charat (0). touppercase () + c.substring(1))。加入(' ')); 文档。write(titleCase(“我是一个更小的茶壶”));

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

我已经使用下面的代码做到了这一点,希望它能帮助你:

<p id="p1">This is a paragraph.</p>

<script>
   const capitalize = (mySentence) => {
      const words = mySentence.split(" ");
      for (let i = 0; i < words.length; i++) {
         words[i] = words[i][0].toUpperCase() + words[i].substr(1);
      }
      return words.join(" ");
   };  
   const result = capitalize('This is a sample text');
   document.getElementById("p1").innerHTML = result;
</script>

下面是字符串中每个单词首字母大写的另一种方法。

使用prototype为String对象创建一个自定义方法。

String.prototype.capitalize = function() {
    var c = '';
    var s = this.split(' ');
    for (var i = 0; i < s.length; i++) {
        c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
    }
    return c;
}
var name = "john doe";
document.write(name.capitalize());

ECMA2017或ES8

const titleCase = (string) => { return string .split(' ') .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length)) .join(' '); }; let result = titleCase('test test test'); console.log(result); Explanation: 1. First, we pass the string "test test test" to our function "titleCase". 2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"] 3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it. 4. In the last, we join the array using space as we split the string by sapce.