How to title case the string in JavaScript
JavaScript doesn’t offer any inbuilt methods to capitalize the first letter of the string.
Let’s write our function to convert the string to title case.
-
convert the string to lowerCase.
-
split the single string into an array of strings.
-
create an array.
-
loop through the array of strings and capitalize the first letter in every string.
-
return the title case string.
function titleCase(str){
str = str.toLowerCase().split(' ');
let final = [ ];
for(let word of str){
final.push(word.charAt(0).toUpperCase()+ word.slice(1));
}
return final.join(' ')
}
titleCase('this is a title case string');
//"This Is A Title Case String"
There is another way to title Case the string by using the CSS.
.main{
text-transform:captialize;
}
Happy coding…