Trying to capitalize the first character in array of strings, why this is not working?
You have to actually re-assign the array element:
for(var i = 1 ; i < newArr.length ; i++){
newArr[i] = newArr[i].charAt(0).toUpperCase();
}
The "toUpperCase()" function returns the new string but does not modify the original.
You might want to check to make sure that newArr[i]
is the empty string first, in case you get an input string with two consecutive dashes.
edit — noted SO contributor @lonesomeday correctly points out that you also need to glue the rest of each string back on:
newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1);
Here is my solution with ES6. This is an example where I store the days of the week in my array and I uppercase them with for... of
loop.
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for (let day of days) {
day = day.charAt(0).toUpperCase() + day.substr(1);
console.log(day);
}
Here is a link to the documentation: for... of loop documentation
In your for
loop, you need to replace the value of newArr[i]
instead of simply evaluating it:
for(var i = 1 ; i < newArr.length ; i++){
newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1);
}