You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将kebab-case转为camelCase?解决代码首字母大写问题

Fixing Your Kebab-Case to CamelCase Conversion Function

Got it, let's break down the issue with your current code. The problem is straightforward: you're capitalizing the first letter of every split word—including the very first one. That's why you end up with MyKebabString instead of the desired myKebabString.

What's Off in the Original Code?

Your map call transforms every item to start with an uppercase letter:

let capital = arr.map(item=> item.charAt(0).toUpperCase() + item.slice(1).toLowerCase());

This works perfectly for every word after the first, but camelCase requires the first word to stay lowercase. We just need to tweak this logic to leave the first word's starting letter untouched.

Updated Solution

Here's a adjusted version that fixes the capitalization issue, plus adds a return statement so you can use the function's output elsewhere:

function camelize(str){
  const wordArr = str.split('-');
  
  // Process each word: keep first word lowercase, capitalize the rest
  const camelCaseArr = wordArr.map((word, index) => {
    if (index === 0) {
      // Ensure the first word starts with lowercase (normalize case if needed)
      return word.charAt(0).toLowerCase() + word.slice(1).toLowerCase();
    }
    // Capitalize first letter of subsequent words, rest stay lowercase
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
  
  const result = camelCaseArr.join('');
  console.log(result);
  return result;
}

// Validate the target case
console.log(camelize("my-kebab-string") === 'myKebabString'); // Logs true

Even More Concise Version

If you prefer shorter code, you can destructure the first word from the array and handle the rest separately:

function camelize(str){
  const [firstWord, ...restWords] = str.split('-');
  return firstWord.toLowerCase() + restWords
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join('');
}

Test Cases to Confirm It Works

  • camelize("my-kebab-string") → myKebabString (your target output)
  • camelize("HELLO-WORLD") → helloWorld (normalizes mixed-case input)
  • camelize("single-word-no-hyphens") → singleWordNoHyphens
  • camelize("test") → test (handles single-word inputs correctly)

内容的提问来源于stack exchange,提问作者Robert Hovhannisyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:57:05