If you need to convert a String to Title Case in Javascript, then you can do one of the following:
Option 1 – Using a for
loop
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++)
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
return str.join(' ');
}
console.log(titleCase("this is an example of some text!"));
Output: This Is An Example Of Some Text!
Option 2 – Using map()
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(' ');
}
console.log(titleCase("this is an example of some text!"));
Output: This Is An Example Of Some Text!
Option 3 – Using replace()
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
console.log(titleCase("this is an example of some text!"));
Output: This Is An Example Of Some Text!