Friday, June 1, 2012

Capitalize the first letter of string in JavaScript


I want to capitalize the first character of a string, but not change the case of any of the other letters. For example:



  • this is a test -> This is a test

  • the Eiffel Tower -> The Eiffel Tower

  • /index.html -> /index.html


Source: Tips4all

13 comments:

  1. Another solution:

    function capitaliseFirstLetter(string)
    {
    return string.charAt(0).toUpperCase() + string.slice(1);
    }

    ReplyDelete
  2. A more object-oriented approach:

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


    And then:

    "hello world".capitalize(); => "Hello world"

    ReplyDelete
  3. Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:

    function capitaliseFirstLetter(string)
    {
    return string[0].toUpperCase() + string.slice(1);
    }

    ReplyDelete
  4. Seems to be easier in CSS...

    <style type="text/css">
    p.capitalize {text-transform:capitalize;}
    </style>
    <p class="capitalize">This is some text.</p>


    from: http://www.w3schools.com/cssref/pr_text_text-transform.asp

    ReplyDelete
  5. If you are wanting to reformat all-caps text, you might want to modify the other examples as such:

    function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
    }


    This will ensure that the following text is changed:

    TEST => Test
    This Is A TeST => This is a test

    ReplyDelete
  6. String.prototype.capitalize = function(){
    return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
    } );
    };


    Usage:

    capitalizedString = someString.capitalize();


    this is a text string => This Is A Text String

    ReplyDelete
  7. Capitalize the first letter of all words in a string:

    function ucFirstAllWords( str )
    {
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
    var j = pieces[i].charAt(0).toUpperCase();
    pieces[i] = j + pieces[i].substr(1);
    }
    return pieces.join(" ");
    }

    ReplyDelete
  8. Here is a function called ucfirst() (short for "upper case first letter"):

    function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
    }


    You can capitalise a string by calling ucfirst("some string") -- for example,

    ucfirst("this is a test") --> "This is a test"


    It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).

    You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in Javascript, when you take a substring of an empty string, you just get an empty string back.

    ReplyDelete
  9. The ucfirst function works if you do it like this

    function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
    }


    Thanks J-P for the aclaration.

    ReplyDelete
  10. If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:

    String.prototype.capitalize = function () {
    return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
    }


    Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.

    ReplyDelete
  11. Okay so I am a Javascript noob. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):

    String name = request.getParameter("name");
    name = name.toUpperCase().charAt(0) + name.substring(1);
    out.println(name);


    Here I get the Variable from a Form,... it also works manually...

    String name = "i am a Smartypants...";
    name = name.toUpperCase().charAt(0) + name.substring(1);
    out.println(name);


    Output: "I am a Smartypants...";

    Good luck everyone.

    ReplyDelete
  12. If I may alter the code a little. I found that if I run an all caps string through this function, nothing happens. So... here is my tid bit. Force the string to lower case first.

    String.prototype.capitalize = function(){
    return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
    }

    ReplyDelete
  13. CoffeeScript

    ucfirst = (str) -> str.substr(0, 1).toUpperCase() + str.substr(1)

    ReplyDelete