What is the best approach to capitalize words in a string?
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
output: "This Is The Worst String Ever"
http://www.mediacollege.com/internet/javascript/text/case-capitalize.html is one of many answers out there.
Google can be all you need for such problems.
A naïve approach would be to split the string by whitespace, capitalize the first letter of each element of the resulting array and join it back together. This leaves existing capitalization alone (e.g. HTML stays HTML and doesn't become something silly like Html). If you don't want that affect, turn the entire string into lowercase before splitting it up.
Using javascript
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
and example in html
<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();">
<input name="outstring" type="text" value="" size="30">
</form>
Basically, you can do string.capitalize() and it'll capitalize every 1st letter of each word.
Source: http://www.mediacollege.com/internet/javascript/text/case-capitalize.html
Since everyone has given you the JavaScript answer you've asked for, I'll throw in that the CSS property text-transform: capitalize will do exactly this.
I realize this might not be what you're asking for - you haven't given us any of the context in which you're running this - but if it's just for presentation, I'd definitely go with the CSS alternative.
John Resig (of jQuery fame ) ported a perl script, written by John Gruber, to JavaScript. This script capitalizes in a more intelligent way, it doesn't capitalize small words like 'of' and 'and' for example.
You can find it here: Title Capitalization in JavaScript