Converting First Charcter of String to Upper Case

This question already has an answer here:

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

  • You are almost there. Instead of uppercasing the entire string, uppercase only the first character.

    Array.prototype.myUcase = function()
    {
        for (var i = 0, len = this.length; i < len; i += 1)
        {
              this[i] = this[i][0].toUpperCase() + this[i].slice(1);
        }
        return this;
    }
    
    var A = ["one", "two", "three", "four"]
    console.log(A.myUcase())
    

    Output

    [ 'One', 'Two', 'Three', 'Four' ]
    

    If you need the upper case for presentation to your views, you can simply use css for do so!

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

    here is the complete fiddle example: http://jsfiddle.net/wV33P/1/


    Use this extension (as per previous SO-answer):

    String.prototype.first2Upper = String.prototype.first2Upper || function(){
     return this.charAt(0).toUpperCase()+this.slice(1);
    }
    //usage
    'somestring'.first2Upper(); //=> Somestring
    

    And for your array using map in combination with this extension would be:

    var numArray = ["one", "two", "three", "four"]
                   .map(function(elem){return elem.first2Upper();});
    // numArray now: ["One", "Two", "Three", "Four"]
    

    See MDN for explanation of and shim for the map method

    链接地址: http://www.djcxy.com/p/17858.html

    上一篇: 只有第一个单词的大写首字母

    下一篇: 将字符串的第一个字符转换为大写