Convert string to Title Case with JavaScript

javascript, title-case

Solution

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>

Problem

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.

Original source

Related problems