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 R
My one line solution:
String.prototype.capitalizeWords = function() {
return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myS = "this actually works!";
myS.capitalizeWords();
>>> This Actually Works
My other solution:
function capitalizeFirstLetter(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeAllWords = function() {
var arr = this.split(" ");
for(var i = 0; i < arr.length; i++) {
arr[i] = capitalizeFirstLetter(arr[i]);
}
return arr.join(" ");
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myStr = "this one works too!";
myStr.capitalizeWords();
>>> This One Works Too
Alternative solution based on Greg Dean answer:
function capitalizeFirstLetter(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeWords = function() {
return this.replace(/\w\S*/g, capitalizeFirstLetter);
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myString = "yes and no";
myString.capitalizeWords()
>>> Yes And No