尝试将字符串数组中的第一个字符大写,为什么这不起作用?

发布于 2024-12-09 09:10:19 字数 524 浏览 0 评论 0原文

我正在尝试编写一个函数,将 list-style-image 转换为 listStyleImage

我想出了一个功能,但它似乎不起作用。有人能指出我这里的问题吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

胡大本事 2024-12-16 09:10:20

您实际上必须重新分配数组元素:

    for(var i = 1 ; i < newArr.length ; i++){
        newArr[i] = newArr[i].charAt(0).toUpperCase();
    }       

“toUpperCase()”函数返回新字符串,但不会修改原始字符串。

您可能需要首先检查以确保 newArr[i] 是空字符串,以防您得到带有两个连续破折号的输入字符串。

编辑 - 指出SO贡献者@lonesomeday正确地指出你还需要将每个字符串的其余部分粘回去:

         newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(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);
已下线请稍等 2024-12-16 09:10:20
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days.map( a => a.charAt(0).toUpperCase() + a.substr(1) );
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days.map( a => a.charAt(0).toUpperCase() + a.substr(1) );
听,心雨的声音 2024-12-16 09:10:20

这是我使用 ES6 的解决方案。这是一个示例,我将一周中的几天存储在数组中,并使用 for...of 循环将它们大写。

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

以下是文档的链接:for ... of 循环文档

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

聽兲甴掵 2024-12-16 09:10:20

for 循环中,您需要替换 newArr[i] 的值,而不是简单地计算它:

for(var i = 1 ; i < newArr.length ; i++){
    newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1);
}

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);
}
不气馁 2024-12-16 09:10:20

从 JavaScript ES6 开始,您可以用一行实现字符串数组的“驼峰化”:

let newArrCamel= newArr.map(item=> item.charAt(0).toUpperCase() + item.substr(1).toLowerCase())

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())
伪心 2024-12-16 09:10:20

这是我使用 slice() 方法的解决方案。

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

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

})

console.log(capitalized)

// 预期输出:
// [“爱丽丝”、“鲍勃”、“查理”、“丹妮尔”]

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

小ぇ时光︴ 2024-12-16 09:10:20

您不需要数组来将连字符和小写字母替换为大写字母 -

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 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
*/
听,心雨的声音 2024-12-16 09:10:20

您需要将大写字母存储回数组中。请参考下面修改后的循环,

for(var i = 1 ; i < newArr.length ; i++)
{
    newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1,newArr[i].length-1);
}

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);
}
橙幽之幻 2024-12-16 09:10:20

有点长,但它基本上可以通过数组完成工作:

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

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");
醉酒的小男人 2024-12-16 09:10:20

substr() 方法返回字符串中起始索引与其后的多个字符之间的部分。来源: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);
}

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

橘虞初梦 2024-12-16 09:10:20

这是另一个解决方案,尽管我玩得太晚了。

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

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

缱倦旧时光 2024-12-16 09:10:20

我们来看看下面的代码。

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

输出: [“周日”,“周一”]

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

山田美奈子 2024-12-16 09:10:20

我最好的方法是:

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

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

杀手六號 2024-12-16 09:10:20
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.
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.
萌辣 2024-12-16 09:10:20

以下是我的做法。

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

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;
}
仅此而已 2024-12-16 09:10:20

请检查下面的代码

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

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);
}
哎呦我呸! 2024-12-16 09:10:20

const 名称 = ['鲍勃', '结婚', '爱丽丝', '詹妮弗'];
const 大写 = 名称.map((名称) => {
返回(
name[0].charAt(0).toUpperCase() + name.slice(1) + ' '

});
console.log(大写)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文