[英]Why do I have to push my string into an array only to join it back again?
So I want to capitalize the starting letter of each word in a string. 因此,我想将字符串中每个单词的起始字母大写。 Here's how I did it: 这是我的操作方式:
function LetterCapitalize(str) {
var arr = str.split(" ");
var newArr = [];
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
newArr.push(newStr.substring(0,1).toUpperCase() + newStr.substring(1,newStr.length));
}
return newArr.join(" ");
}
This code is correct and the first letter of every word in the string was capitalized. 此代码是正确的,并且字符串中每个单词的第一个字母都大写。 However, when I tried to shorten my code like this, it only returned the last word of the string with the first letter capitalized, but nothing else: 但是,当我尝试像这样缩短代码时,它仅返回字符串的最后一个单词,首字母大写,但没有其他内容:
function LetterCapitalize(str) {
var arr = str.split(" ");
var newArr = [];
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
}
return newStr.substring(0,1).toUpperCase() + newStr.substring(1,newStr.length);
}
Basically, what I did was remove the part where I push the new string into a new array, only to join it back into a string. 基本上,我所做的是删除将新字符串推入新数组的部分,只是将其重新组合为字符串。
Problem is in the for
loop part code. 问题出在for
循环零件代码中。 Here in every iteration the newstr
get the value of arr[i].toString();
在这里,每次迭代时newstr
获得arr[i].toString();
的值arr[i].toString();
and the old value ie arr[i-1].toString();
和旧值,即arr[i-1].toString();
which is in newStr
is overwritten. 这在newStr
被覆盖。 Hence only the last iteration value is stored in newStr
因此,只有最后一次迭代值存储在newStr
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
}
Try this: 尝试这个:
function LetterCapitalize(str) { var arr = str.split(" "); var newStr = ""; for(i = 0; i < arr.length; i++) { var temp = arr[i].toString(); newStr = newStr + temp.substring(0,1).toUpperCase() + temp.substring(1,temp.length)+" "; } return newStr; } alert(LetterCapitalize("hello i am rohit "));
Perhaps you got confused by the return in the MAP functionality: 也许您对MAP功能的返回感到困惑:
function LetterCapitalize(str) { var arr = str.split(" "), newArr = arr.map( function(word) { return word.substring(0,1).toUpperCase() + word.substring(1); }); return newArr.join(" "); } alert(LetterCapitalize("This is a test"))
You may achieve this through replace function without splitting. 您可以通过替换功能来实现此目的而无需拆分。
function LetterCapitalize(str) {
return str.replace(/(^| )([a-z])/g, function(x,y,z) {
return y+z.toUpperCase()
}
)
}
console.log(LetterCapitalize('foo bar buz'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.