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));
2
  • 1
    Possible duplicate of Convert hyphens to camel case (camelCase) Commented Jun 15, 2017 at 4:06
  • This seems to be a classical example of an xy problem: The OP actually wants to convert a kebab case string to a lower camel case string but they ask about how to capitalize strings in an array... Commented Dec 6, 2024 at 14:58

17 Answers 17

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);
Sign up to request clarification or add additional context in comments.

7 Comments

That gives listSI. You need + newArr[i].substr(1)
If iterating array from 1, expression won't get applied when it's only single element in array. Loop should have var i = 0.
@TeoDragovic the original question wanted to skip the first character; in other words, a single character value like "a" should result in the same string, "a".
do you need to use charAt or could you skip this step?
@coder123 you could use newArr[i][0].toUpperCase() if you prefer.
|
9
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days.map( a => a.charAt(0).toUpperCase() + a.substr(1) );

1 Comment

You should consider adding some explanation, as well as properly formatting the code you posted.
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

Comments

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

Comments

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

Comments

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"]

Comments

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
*/

Comments

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

Comments

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

Comments

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

Comments

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

Comments

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"]

Comments

1

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'])

Comments

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.

Comments

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

Comments

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

Comments

0

const names = ['bob', 'marry', 'alice', 'jenifer']; const capitalized = names.map((name) => { return( name[0].charAt(0).toUpperCase() + name.slice(1) + ' ' ) }); console.log(capitalized)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.