Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
ryryan Avatar asked Feb 25 '11 20:02

ryryan


People also ask

Can the first letter of a variable be capitalized?

It depends on the language. In JavaScript, you can technically use capitalized variable names, but the convention is to use lowercase words for variable names, and capitalized words for constructors.

How can I uppercase the first letter of a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize the first letter of a variable in R?

Convert First letter of every word to Uppercase in R Programming – str_to_title() Function. str_to_title() Function in R Language is used to convert the first letter of every word of a string to Uppercase and the rest of the letters are converted to lower case.

How do you capitalize variables?

APA's rules for variables are as follows (p. 99): Do not capitalize effects or variables unless they appear with multiplication signs.


1 Answers

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 Αλφα"
like image 125
Peter Olson Avatar answered Oct 21 '22 00:10

Peter Olson