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

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

    It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter in CSS and apply text-transform:capitalize;

    So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase and add something like below in your CSS:

    .first-letter-uppercase:first-letter {
        text-transform:capitalize;
    }
    

    Also the alternative option is JavaScript, so the best gonna be something like this:

    function capitalizeTxt(txt) {
      return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
    }
    

    and call it like:

    capitalizeTxt('this is a test'); // return 'This is a test'
    capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
    capitalizeTxt('/index.html');  // return '/index.html'
    capitalizeTxt('alireza');  // return 'Alireza'
    

    If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:

    String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    

    and call it as below:

    'this is a test'.capitalizeTxt(); // return 'This is a test'
    'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
    '/index.html'.capitalizeTxt();  // return '/index.html'
    'alireza'.capitalizeTxt();  // return 'Alireza'
    

提交回复
热议问题