Title Case a Sentence-freecodecamp算法题目

Title Case a Sentence(中单词首字母大写)

  1. 要求
    • 确保字符串的每个单词首字母都大写,其余部分小写。
    • 像'the'和'of'这样的连接符同理。
  2. 思路
    • 将句子小写化后用.split(" ")将句子分隔成各单词组成的数组,
    • 再用for循环将数组中每个单词用.split('')分隔成各个字母组成的数组,将数组中第一个元素大写,即首字母大写后用.join('')将字母合成单词
    • 最后将各数组单词用.join(' ')合成句子
  3. 代码
    1.  1 function titleCase(str) {
       2   // 请把你的代码写在这里
       3   var temp1 = str.toLowerCase().split(" ");
       4   for (var i =0;i<temp1.length;i++){
       5     temp1[i] = temp1[i].split('');
       6     temp1[i][0]= temp1[i][0].toUpperCase();
       7     temp1[i] = temp1[i].join('');
       8   }
       9   str = temp1.join(' ');
      10   return str;
      11 }
      12 
      13 titleCase("I'm a little tea pot");
  4. 相关链接
    • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/split
原文地址:https://www.cnblogs.com/ahswch/p/9292886.html