Uppercase first letter of variable

Use the .replace[MDN] function to replace the lowercase letters that begin a word with the capital letter.

var str = "hello world";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Hello World"

Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.

var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"

Much easier way:

$('#test').css('textTransform', 'capitalize');

I have to give @Dementic some credit for leading me down the right path. Far simpler than whatever you guys are proposing.


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)


just wanted to add a pure javascript solution ( no JQuery )

function capitalize(str) {
  strVal = '';
  str = str.split(' ');
  for (var chr = 0; chr < str.length; chr++) {
    strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
  }
  return strVal
}

console.log(capitalize('hello world'));

I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.

myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"

I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".