I found a solution to the code that makes every first letter of a string to uppercase. But for me it's not the simplest version to understand. Is there perhaps more easier way to rewrite it?
Let me try to explain the code for you.
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
Let's say we have the sentence "javascript is cool" and we want to capitalize that.
So we start out by declaring the variable splitStr. This is an array of every word in the sentence. This array is obtained by "splitting" the string by the spaces. As a result, in our case, splitStr is ["javascript", "is", "cool"].
Now, we go into this for loop that loops through every element in splitStr. For every element in splitStr, the loop replaces that element with a word formed by concatenating the capitalized first letter of the corresponding word in the array, followed by the rest of the word. For example:
javascript = J + avascript = Javascript
This happens for every word in the array. In the end, the array now contains: ["Javascript", "Is", "Cool"].
At the every end, we join the array together separating each element with a space which results in the string "Javascript Is Cool".