简体   繁体   中英

Transformation of each first character in a string to uppercase

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM