Convert string to Title Case with JavaScript
Is there a simple way to convert a string to Title Case? E.g. john smith
becomes John Smith
. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.
Solution 1:
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
Solution 2:
If a CSS solution meets your needs, you can apply the text-transform CSS style to your controls:
text-transform: capitalize;
Just be aware that this will transform:hello world
to Hello World
HELLO WORLD
to HELLO WORLD
(no change)emily-jane o'brien
to Emily-jane O'brien
(incorrect)Maria von Trapp
to Maria Von Trapp
(incorrect)
Solution 3:
A slightly more elegant way, adapting Greg Dean's function:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();