Trying to capitalize the first character in array of strings, why this is not working?
I'm trying to write a function that converts for example list-style-image
to listStyleImage
.
I came up with a function but it seems not working. Can anybody point me to the problem here ?
var myStr = "list-style-image";
function camelize(str){
var newStr = "";
var newArr = [];
if(str.indexOf("-") != -1){
newArr = str.split("-");
for(var i = 1 ; i < newArr.length ; i++){
newArr[i].charAt(0).toUpperCase();
}
newStr = newArr.join("");
}
return newStr;
}
console.log(camelize(myStr));
Solution 1:
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);
Solution 2:
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
Solution 3:
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);
}