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.