There's a good answer here:
function toTitleCase(str) {
return str.replace(/wS*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…