Capitalize First Letter of each word in a String
by Eugene Manager
HTML
<div id='element'>
</div>
JavaScript
function titleCase(text) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++){
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'"){
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1))) firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2))) firstLtr = 3;
}
if (firstLtr == 3) firstLtr = 1;
else firstLtr = 0;
}
if (firstLtr == 2){
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
return text;
}
document.write(titleCase("I'm a little tea pork, i love: 'google','facebook'"));