美文网首页
Title Case a Sentence | Free Cod

Title Case a Sentence | Free Cod

作者: Marks | 来源:发表于2017-05-02 10:39 被阅读11次

    确保字符串的每个单词首字母都大写,其余部分小写
    titleCase("I'm a little tea pot") should return a string.
    titleCase("I'm a little tea pot") should return "I'm A Little Tea Pot".
    titleCase("sHoRt AnD sToUt") should return "Short And Stout".
    titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") should return "Here Is My Handle Here Is My Spout".

    //方法一:charAt() + slice
    function titleCase(str) {
      var arr = str.toLowerCase().split(" ");
      for(var i=0;i<arr.length;i++){
       arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
      }
      return arr.join(" ");
    }
    titleCase("I'm a little tea pot");```
    
    

    //方法二:charAt() + replace
    function titleCase(str) {
    var arr = str.toLowerCase().split(" ");
    var result = arr.map(function(val){
    return val.replace(val.charAt(0),val.charAt(0).toUpperCase());
    });
    return result.join(" ");
    }

    titleCase("I'm a little tea pot");

    https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Title-Case-A-Sentence
    
    
    
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:Title Case a Sentence | Free Cod

          本文链接:https://www.haomeiwen.com/subject/kqrctxtx.html