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
Is There a Reason Declval Returns Add_Rvalue_Reference Instead of Add_Lvalue_Reference
Code Browsing, Refactoring, Auto Completion in Emacs
Template Tricks with Const Char* as a Non-Type Parameter
Performance Degradation Due to Default Initialisation of Elements in Standard Containers
Std Linker Error with Apple Llvm 4.1
How to Determine the Correct Size of a Qtablewidget
Understanding Boost::Disjoint_Sets
Avoid Exponential Grow of Const References and Rvalue References in Constructor
Converting a Vector<Int> to String
Why Does Visual Studio Not Perform Return Value Optimization (Rvo) in This Case
How to Test If a Constexpr Function Is Evaluated at Compile Time
Is There Any G++ Option to Dump Class Layout and Vtables
How to Quickly Enumerate Directories on Win32
How to Execute a Command and Get Return Code Stdout and Stderr of Command in C++
Sfinae and Partial Class Template Specializations
Why Gcc Does Not Use Load(Without Fence) and Store+Sfence for Sequential Consistency
Using Continue in a Switch Statement
How to Create a Type List (For Variadic Templates) That Contains N-Times the Same Type