Convert First Letter in String to Uppercase

How can I capitalize the first letter of each word in a string using JavaScript?

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

function titleCase(str) {   var splitStr = str.toLowerCase().split(' ');   for (var i = 0; i < splitStr.length; i++) {       // You do not need to check if i is larger than splitStr length, as your for does that for you       // Assign it back to the array       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);        }   // Directly return the joined string   return splitStr.join(' '); }
document.write(titleCase("I'm a little tea pot"));

How to capitalize the first letter of word in a string using Java?

If you only want to capitalize the first letter of a string named input and leave the rest alone:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.

Capitalizing the first letter of a string only

What about using ToUpper on the first char and ToLower on the remaining string?

string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();

convert a string such that the first letter is uppercase and everythingelse is lower case

Just use str.title():

In [73]: a, b = "italic","ITALIC"

In [74]: a.title(), b.title()
Out[74]: ('Italic', 'Italic')

help() on str.title():

S.title() -> string

Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.


Related Topics



Leave a reply



Submit