How do I make the first letter of a string uppercase in JavaScript?

前端 未结 30 2212
南方客
南方客 2020-11-21 05:00

How do I make the first letter of a string uppercase, but not change the case of any of the other letters?

For example:

  • \"this is a test\"
30条回答
  •  一向
    一向 (楼主)
    2020-11-21 05:28

    The basic solution is:

    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    console.log(capitalizeFirstLetter('foo')); // Foo

    Some other answers modify String.prototype (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).

    ...and then, there is so much more to this question when you consider internationalisation, as this astonishingly good answer (buried below) shows.

    If you want to work with Unicode code points instead of code units (for example to handle Unicode characters outside of the Basic Multilingual Plane) you can leverage the fact that String#[@iterator] works with code points, and you can use toLocaleUpperCase to get locale-correct uppercasing:

    function capitalizeFirstLetter([ first, ...rest ], locale = navigator.language) {
      return [ first.toLocaleUpperCase(locale), ...rest ].join('');
    }
    
    console.log(capitalizeFirstLetter('foo')); // Foo
    console.log(capitalizeFirstLetter("

提交回复
热议问题