Convert string to title case with JavaScript

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

    For those of us who are scared of regular expressions (lol):

    function titleCase(str)
    {
        var words = str.split(" ");
        for ( var i = 0; i < words.length; i++ )
        {
            var j = words[i].charAt(0).toUpperCase();
            words[i] = j + words[i].substr(1);
        }
        return words.join(" ");
    }

提交回复
热议问题