开发者

Trying to capitalize the first character in array of strings, why this is not working?

开发者 https://www.devze.com 2023-04-12 08:29 出处:网络
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 ?

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("");
    }开发者_StackOverflow中文版
    return newStr;
}

console.log(camelize(myStr));


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


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

days.map( a => a.charAt(0).toUpperCase() + a.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);
}


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


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


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


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


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


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


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


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


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.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号