I have single string and I want to convert this to title case. JS is not providing built in function.
var difficulty = "easy"; // medium, hard
difficulty[0].toUpperCase();
document.write(difficulty) // It is printing in small.
I have single string and I want to convert this to title case. JS is not providing built in function.
var difficulty = "easy"; // medium, hard
difficulty[0].toUpperCase();
document.write(difficulty) // It is printing in small.
If you don't want to repeat the code multiple times, you can add a method to the String prototype, that would allow you to easily reuse the functionality many times
String.prototype.titleCase = function () {
var sentence = this.toLowerCase().split(" ");
for(var i = 0; i< sentence.length; i++){
sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
}
return sentence.join(" ");
}
var difficulty = "easy";
document.write(difficulty.titleCase());
document.write("<br/>")
document.write("medium".titleCase());
document.write("<br/>")
document.write("hard".titleCase());
This will also work on words with spaces, so very easy // would give "Very Easy"