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. Here in every iteration the newstr
get the value of arr[i].toString();
and the old value i.e arr[i-1].toString();
which is in newStr
is overwritten. Hence only the last iteration value is stored in 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 "));