Convert string to title case with JavaScript

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

    Without using regex just for reference:

    String.prototype.toProperCase = function() {
      var words = this.split(' ');
      var results = [];
      for (var i = 0; i < words.length; i++) {
        var letter = words[i].charAt(0).toUpperCase();
        results.push(letter + words[i].slice(1));
      }
      return results.join(' ');
    };
    
    console.log(
      'john smith'.toProperCase()
    )

提交回复
热议问题