18

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));
NAND
  • 663
  • 8
  • 22
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
  • Possible duplicate of [Convert hyphens to camel case (camelCase)](https://stackoverflow.com/questions/6660977/convert-hyphens-to-camel-case-camelcase) – Sangwin Gawande Jun 15 '17 at 04:06

16 Answers16

22

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);
Pointy
  • 405,095
  • 59
  • 585
  • 614
9
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days.map( a => a.charAt(0).toUpperCase() + a.substr(1) );
MrCorote
  • 565
  • 8
  • 21
  • 2
    You should consider adding some explanation, as well as properly formatting the code you posted. – norok2 Jul 11 '18 at 20:03
7

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

martinkzn
  • 103
  • 2
  • 9
6

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);
}
RoccoC5
  • 4,185
  • 16
  • 20
3

Since JavaScript ES6 you can achieve the "camelization" of an array of strings with a single line:

let newArrCamel= newArr.map(item=> item.charAt(0).toUpperCase() + item.substr(1).toLowerCase())
afxentios
  • 2,502
  • 2
  • 21
  • 24
3

Here is my solution using the slice() method.

const names = ["alice", "bob", "charlie", "danielle"]

const capitalized = names.map((name) => {
    return name[0].toUpperCase() + name.slice(1)

})

console.log(capitalized)

// Expected output: // ["Alice", "Bob", "Charlie", "Danielle"]

Stanflows
  • 41
  • 4
2

A little bit longer but it gets the job done basically playing with arrays:

function titleCase(str) {
  var arr = [];
  var arr2 = [];
  var strLower = "";
  var strLower2 = "";
  var i;
  arr = str.split(' ');

  for (i=0; i < arr.length; i++) {

    arr[i] = arr[i].toLowerCase();
    strLower = arr[i];
    arr2 = strLower.split('');
    arr2[0] = arr2[0].toUpperCase();
    strLower2 = arr2.join('');
    arr[i] = strLower2;
  }

  str = arr.join(' ');

  return str;
}

titleCase("I'm a little tea pot");
Jmorazano
  • 47
  • 8
2

The substr() method returns the part of a string between the start index and a number of characters after it. Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for (let day of days) {
  day = day.substr(0, 1).toUpperCase() + day.substr(1);
  console.log(day);
}
IKavanagh
  • 6,089
  • 11
  • 42
  • 47
2

You don't need the array to replace a hyphen and a lowercase letter with the uppercase-

function camelCase(s){
    var rx=  /\-([a-z])/g;
    if(s=== s.toUpperCase()) s= s.toLowerCase();
    return s.replace(rx, function(a, b){
        return b.toUpperCase();
    });
}

camelCase("list-style-image")

/*  returned value: (String)
listStyleImage
*/
kennebec
  • 102,654
  • 32
  • 106
  • 127
2

you need to store the capitalized letter back in the array. Please refer the modified loop below,

for(var i = 1 ; i < newArr.length ; i++)
{
    newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1,newArr[i].length-1);
}
Vivek Viswanathan
  • 1,968
  • 18
  • 26
1

Here's another solution though I am so late in the game.

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

let capitalize = days.map(day => day.charAt(0).toUpperCase() + day.slice(1).toLowerCase());

console.log(capitalize);
kaleem
  • 59
  • 2
  • 8
1

Let's checkout the code below.

['sun','mon'].reduce((a,e)=> { a.push(e.charAt(0).toUpperCase()+e.substr(1)); return a; },[]);

Output: ["Sun", "Mon"]

Masum Billah
  • 2,209
  • 21
  • 20
0
function titleCase(str){    // my codelooks like Jmorazano but i only use 4 var.
var array1 = [];
var array2 = []; 
var array3 = "";
var i;
array1 = str.split(" ");
for (i=0; i < array1.length; i++) {
array1[i]= array1[i].toLowerCase();
array2=array1[i].split("");
array2[0]=array2[0].toUpperCase();
array3 = array2.join("");
array1[i] = array3;}

str = array1.join(' ');
return str;}
titleCase("I AM WhO i aM"); //Output:I Am Who I Am
// my 1st post.
0

Here is how I would go about it.

function capitalizeFirst(arr) {
  if (arr.length === 1) {
    return [arr[0].toUpperCase()];
  }
  let newArr = [];
  for (let val of arr) {
    let value = val.split("");
    let newVal = [value[0].toUpperCase(), ...value.slice(1)];
    newArr.push(newVal.join(""));
  }
  return newArr;
}
Roninho
  • 336
  • 2
  • 7
0

Please check this code below

 var months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'november', 'decembar'];

for(let month of months){
    month = month.charAt(0).toUpperCase() + month.substr(1);
    console.log(month);
}
0

my best way is:

function camelCase(arr) {
  let calc = arr.map(e => e.charAt(0).toUpperCase() + e.slice(1)).join('')
  console.log(calc)
  return calc;
}

// Test
camelCase(['Test', 'Case'])