[英]Transformation of each first character in a string to uppercase
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.假设我们有一句话“javascript is cool”,我们想把它大写。
So we start out by declaring the variable splitStr.所以我们首先声明变量 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"].
因此,在我们的例子中,splitStr 是 ["javascript", "is", "cool"]。
Now, we go into this for loop that loops through every element in splitStr.现在,我们进入这个 for 循环,它遍历 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.
对于 splitStr 中的每个元素,循环用一个单词替换该元素,该单词通过连接数组中相应单词的大写首字母,然后是单词的其余部分而形成。 For example:
例如:
javascript = J + avascript = Javascript javascript = J + avascript = Javascript
This happens for every word in the array.数组中的每个单词都会发生这种情况。 In the end, the array now contains: ["Javascript", "Is", "Cool"].
最后,数组现在包含:["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".在每一端,我们将数组连接在一起,用空格分隔每个元素,从而产生字符串“Javascript Is Cool”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.