Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  97] [ 1]  / answers: 1 / hits: 59773  / 13 Years ago, wed, october 12, 2011, 12:00:00

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));

More From » arrays

 Answers
12

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);

[#89654] Tuesday, October 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anyssaarielles

Total Points: 415
Total Questions: 107
Total Answers: 92

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;