美文网首页前端Freecode camp
Title Case a Sentence -- Freecod

Title Case a Sentence -- Freecod

作者: Marks | 来源:发表于2017-03-23 15:23 被阅读853次

    确保字符串的每个单词首字母都大写,其余部分小写。
    像'the'和'of'这样的连接符同理。
    当你完成不了挑战的时候,记得开大招'Read-Search-Ask'。
    这是一些对你有帮助的资源:
    String.split()
    Test:
    titleCase("I'm a little tea pot") 应该返回一个字符串
    titleCase("I'm a little tea pot") 应该返回 "I'm A Little Tea Pot".
    titleCase("sHoRt AnD sToUt") 应该返回 "Short And Stout".
    titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") 应该返回 "Here Is My Handle Here Is My Spout".

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

    //方法2:map() + charAt() + slice()
    function titleCase(str) {
    return str.toLowerCase().split(" ").map(function(word){
    return (word.charAt(0).toUpperCase() + word.slice(1));
    }).join(" ");
    }
    console.log(titleCase("I'm a little tea pot "));```

    //方法3:map() + replace()
    function titleCase(str) {
     return str.toLowerCase().split(" ").map(function(word){
        return word.replace(word[0],word[0].toUpperCase());
     }).join(" ");
    }
    console.log(titleCase("I'm a little tea pot"));```
    
    

    //错错错
    function titleCase(str) {
    arr=str.toLowerCase().split(' ');
    for(var i = 0;i<arr.length;i++){
    var arr2=arr[i].replace(arr[i].charAt(0),arr[i].charAt(0).toUpperCase());
    }
    return arr2;
    }
    console.log(titleCase("I'm a little tea pot"));//Pot```

    Copy from https://medium.freecodecamp.com/three-ways-to-title-case-a-sentence-in-javascript-676a9175eb27#.s74dahc0m

    相关文章

      网友评论

        本文标题:Title Case a Sentence -- Freecod

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