Uppercase first letter of variable

后端 未结 23 1363
粉色の甜心
粉色の甜心 2020-11-30 20:55

I have searched over the web can can\'t find anything to help me. I want to make the first letter of each word upper case within a variable.

So far i have tried:

相关标签:
23条回答
  • 2020-11-30 21:06
    var mystring = "hello World"
    mystring = mystring.substring(0,1).toUpperCase() + 
    mystring.substring(1,mystring.length)
    
    console.log(mystring) //gives you Hello World
    
    0 讨论(0)
  • 2020-11-30 21:06
    var ar = 'foo bar spam egg'.split(/\W/);
    for(var i=0; i<ar.length; i++) {
      ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1) 
    }
    ar.join(' '); // Foo Bar Spam Egg
    
    0 讨论(0)
  • 2020-11-30 21:07
    var country= $('#country').val();
    
    var con=country[0].toUpperCase();
    
    ctr= country.replace(country[0], con);
       
    

    no need to create any function just jugaaar

    0 讨论(0)
  • 2020-11-30 21:08

    Without JQuery

    String.prototype.ucwords = function() {
        str = this.trim();
        return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(s){
            return s.toUpperCase();
        });
    };
    
    console.log('hello world'.ucwords()); // Display Hello World
    
    0 讨论(0)
  • 2020-11-30 21:09

    http://phpjs.org/functions/ucwords:569 has a good example

    function ucwords (str) {
        return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
            return $1.toUpperCase();
        });
    }
    

    (omitted function comment from source for brevity. please see linked source for details)

    EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

    0 讨论(0)
  • 2020-11-30 21:11

    You can use text-transform: capitalize; for this work -

    HTML -

    <input type="text" style="text-transform: capitalize;" />
    

    JQuery -

    $(document).ready(function (){
       var asdf = "WERTY UIOP";
       $('input').val(asdf.toLowerCase());
    });
    

    Try This

    Note: It's only change visual representation of the string. If you alert this string it's always show original value of the string.

    0 讨论(0)
提交回复
热议问题