Convert string to title case with JavaScript

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

    I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call toLowerCase() on your string first.

    function title(str) {
      return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
    }
    

    You can add this to your string prototype which will allow you to 'my string'.toTitle() as follows:

    String.prototype.toTitle = function() {
      return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
    }
    

    Example:

    String.prototype.toTitle = function() {
      return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
    }
    
    console.log('all lower case ->','all lower case'.toTitle());
    console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
    console.log("I'm a little teapot ->","I'm a little teapot".toTitle());

提交回复
热议问题