[javascript] Uppercase first letter of variable

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:

toUpperCase();

And had no luck, as it uppercases all letters.

This question is related to javascript jquery

The answer is


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

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


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.

_x000D_
_x000D_
var str = "???? ????????? björn über ñaque a?fa";_x000D_
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {_x000D_
    return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "???? ????????? Björn Über Ñaque ??fa"
_x000D_
_x000D_
_x000D_


Similar questions with javascript tag:

Similar questions with jquery tag: