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?
-
Hi! Please tag with the language you're using. – Mar 22 '20 at 17:46
1 Answers
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".

- 491
- 5
- 14
-
And a split string into array like ["javascript", "is", "cool"] means three elements, which are the length of that variable, right? – Markus Mar 22 '20 at 19:44
-