Convert string to title case with JavaScript

后端 未结 30 2824
夕颜
夕颜 2020-11-21 06:40

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I\'m not looking for something complicated like John R

30条回答
  •  执念已碎
    2020-11-21 07:41

    My one line solution:

    String.prototype.capitalizeWords = function() {
        return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
    };
    

    Then, you can call the method capitalizeWords() on any string. For example:

    var myS = "this actually works!";
    myS.capitalizeWords();
    
    >>> This Actually Works
    

    My other solution:

    function capitalizeFirstLetter(word) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    }
    String.prototype.capitalizeAllWords = function() {
        var arr = this.split(" ");
        for(var i = 0; i < arr.length; i++) {
            arr[i] = capitalizeFirstLetter(arr[i]);
        }
        return arr.join(" ");
    };
    

    Then, you can call the method capitalizeWords() on any string. For example:

    var myStr = "this one works too!";
    myStr.capitalizeWords();
    
    >>> This One Works Too
    

    Alternative solution based on Greg Dean answer:

    function capitalizeFirstLetter(word) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    }
    String.prototype.capitalizeWords = function() {
        return this.replace(/\w\S*/g, capitalizeFirstLetter);
    };
    

    Then, you can call the method capitalizeWords() on any string. For example:

    var myString = "yes and no";
    myString.capitalizeWords()
    
    >>> Yes And No
    

提交回复
热议问题