Convert string to title case with JavaScript

后端 未结 30 2829
夕颜
夕颜 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:42

    Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.

    /**
     * @param String str The text to be converted to titleCase.
     * @param Array glue the words to leave in lowercase. 
     */
    var titleCase = function(str, glue){
        glue = (glue) ? glue : ['of', 'for', 'and'];
        return str.replace(/(\w)(\w*)/g, function(_, i, r){
            var j = i.toUpperCase() + (r != null ? r : "");
            return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
        });
    };
    

    Hope this helps you out.

    edit

    If you want to handle leading glue words, you can keep track of this w/ one more variable:

    var titleCase = function(str, glue){
        glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
        var first = true;
        return str.replace(/(\w)(\w*)/g, function(_, i, r) {
            var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
            var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
            first = false;
            return result;
        });
    };
    

提交回复
热议问题