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

前端 未结 30 2199
南方客
南方客 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:20

    Use:

    var str = "ruby java";
    
    console.log(str.charAt(0).toUpperCase() + str.substring(1));

    It will output "Ruby java" to the console.

    0 讨论(0)
  • 2020-11-21 05:20
    function capitalize(s) {
        // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
        return s[0].toUpperCase() + s.substr(1);
    }
    
    
    // examples
    capitalize('this is a test');
    => 'This is a test'
    
    capitalize('the Eiffel Tower');
    => 'The Eiffel Tower'
    
    capitalize('/index.html');
    => '/index.html'
    
    0 讨论(0)
  • 2020-11-21 05:22

    We could get the first character with one of my favorite RegExp, looks like a cute smiley: /^./

    String.prototype.capitalize = function () {
      return this.replace(/^./, function (match) {
        return match.toUpperCase();
      });
    };
    

    And for all coffee-junkies:

    String::capitalize = ->
      @replace /^./, (match) ->
        match.toUpperCase()
    

    ...and for all guys who think that there's a better way of doing this, without extending native prototypes:

    var capitalize = function (input) {
      return input.replace(/^./, function (match) {
        return match.toUpperCase();
      });
    };
    
    0 讨论(0)
  • 2020-11-21 05:23

    For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:

    //es5
    function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    capitalize("alfredo")  // => "Alfredo"
    capitalize("Alejandro")// => "Alejandro
    capitalize("ALBERTO")  // => "Alberto"
    capitalize("ArMaNdO")  // => "Armando"
    
    // es6 using destructuring 
    const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
    
    0 讨论(0)
  • 2020-11-21 05:25

    Checkout this solution:

    var stringVal = 'master';
    stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master 
    
    0 讨论(0)
  • 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("                                                                    
    0 讨论(0)
提交回复
热议问题